Text thinning is generally used when making map-related needs. I only implemented this method when implementing a function for the company's map engine. I have simplified it here and operate it on an ordinary Canvas. does not introduce the concept of map
Effect Collision detectionCalculate the range occupied by text in canvas
// Calculate the width required for text var p = { x: 10, y: 10, name: test text}; var measure = ctx.measureText(p.name); // Find the maximum space occupied by text in the canvas drawing board y coordinate var maxX = measure.width + px; // Find the maximum y coordinate occupied by text in the canvas drawing board // Canvas can only calculate the width of text, but not the height of text. So just use the width of the text divided by the number of text to calculate an approximate var maxY = measure.width / p.name.length + py;var min = { x: px, y: py };var max = { x: maxX, y: maxY }; // bounds is the range occupied by the text in the canvas. // When taking point coordinates as the minimum range, it will be more accurate to set textAlign and textBaseline in the following way. // If displayed at different locations, the maximum and minimum points of the range also need to be adjusted // ctx.textAlign = left; // ctx.textBaseline = top;var bounds = new Bounds(min, max);
Bounds range object
/** * Define range objects */function Bounds(min, max) { this.min = min; this.max = max;}/** * Determine whether the range intersects with another range */Bounds.prototype.intersects = function(bounds) { var min = this.min, max = this.max, min2 = bounds.min, max2 = bounds.max, xIntersects = max2.x >= min.x && min2.x <= max.x, yIntersects = max2.y >= min.y && min2.y <= max.y; return xIntersects && yIntersects;};
Detection
// Before each drawing, perform range intersection detection with the drawn text // If an intersection is found, give up drawing the current text, otherwise draw and store the drawn text list for (var index in _textBounds) { // Loop all The drawn text range is tested to see if it intersects with the current text range. If there is an intersection, it means it will collide, and the text is skipped. var pointBounds = _textBounds[index]; if (pointBounds.intersects(bounds)) { return; }}_textBounds.push(bounds);ctx.fillStyle = red;ctx.textAlign = left;ctx.textBaseline = top;ctx.fillText(p.name, px, py);Example, code address
Example address: example
For details, you can view the complete code: Github address
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.