需求背景
一般在做地图相关的需求是才会用到文字抽稀,我也是在为公司的地图引擎实现一个功能时才实现了该方法,在这里将其简化了,就在普通的 Canvas 上进行操作,并没有引入地图概念
效果
碰撞检测
计算文字在 canvas 中所占据的范围
1// 计算文字所需的宽度 2var p = { 3 x: 10, 4 y: 10, 5 name: "测试文字" 6}; 7var measure = ctx.measureText(p.name); 8// 求出文字在 canvas 画板中占据的最大 y 坐标 9var maxX = measure.width + p.x; 10// 求出文字在 canvas 画板中占据的最大 y 坐标 11// canvas 只能计算文字的宽度,并不能计算出文字的高度。所以就利用文字的宽度除以文字个数计算个大概 12var maxY = measure.width / p.name.length + p.y; 13 14var min = { x: p.x, y: p.y }; 15var max = { x: maxX, y: maxY }; 16// bounds 为该文字在 canvas 中所占据的范围。 17// 在取点位坐标作为最小范围时,textAlign、textBaseline 按照以下方式设置会比较准确。 18// 如设置在不同的位置展示,范围最大、最小点也需进行调整 19// ctx.textAlign = "left"; 20// ctx.textBaseline = "top"; 21var bounds = new Bounds(min, max);
Bounds 范围对象
1/** 2* 定义范围对象 3*/ 4function Bounds(min, max) { 5 this.min = min; 6 this.max = max; 7} 8 9/** 10* 判断范围是否与另外一个范围有交集 11*/ 12Bounds.prototype.intersects = function(bounds) { 13 var min = this.min, 14 max = this.max, 15 min2 = bounds.min, 16 max2 = bounds.max, 17 xIntersects = max2.x >= min.x && min2.x <= max.x, 18 yIntersects = max2.y >= min.y && min2.y <= max.y; 19 20 return xIntersects && yIntersects; 21};
检测
1// 每次绘制之前先与已绘制的文字进行范围交叉检测 2// 如发现有交叉,则放弃绘制当前文字,否则绘制并存入已绘制文字列表 3for (var index in _textBounds) { 4 // 循环所有已绘制的文字范围,检测是否和当前文字范围有交集,如果有交集说明会碰撞,则跳过该文字 5 var pointBounds = _textBounds[index]; 6 if (pointBounds.intersects(bounds)) { 7 return; 8 } 9} 10 11_textBounds.push(bounds); 12ctx.fillStyle = "red"; 13ctx.textAlign = "left"; 14ctx.textBaseline = "top"; 15ctx.fillText(p.name, p.x, p.y);
示例、代码地址
示例地址:示例
具体可查看完整代码: Github 地址