需求背景 一般在做地图相关的需求是才会用到文字抽稀,我也是在为公司的地图引擎实现一个功能时才实现了该方法,在这里将其简化了,就在普通的 Canvas 上进行操作,并没有引入地图概念
效果
碰撞检测 计算文字在 canvas 中所占据的范围 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 var p = { x: 10 , y: 10 , name: "测试文字" }; var measure = ctx.measureText(p.name);var maxX = measure.width + p.x;var maxY = measure.width / p.name.length + p.y;var min = { x : p.x, y : p.y };var max = { x : maxX, y : maxY };var bounds = new Bounds(min, max);
Bounds 范围对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 function Bounds (min, max ) { this .min = min; this .max = max; } 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; };
检测 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 for (var index in _textBounds) { 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, p.x, p.y);
示例、代码地址 示例地址:示例 具体可查看完整代码: Github 地址