Canvas 文字碰撞检测并抽稀的方法
碰撞检测 计较笔墨在 canvas 中所占有的范畴 // 计较笔墨所需的宽度 var p = { x: 10, y: 10, name: "测试笔墨" }; var measure = ctx.measureText(p.name); // 求出笔墨在 canvas 画板中占有的最大 y 坐标 var maxX = measure.width + p.x; // 求出笔墨在 canvas 画板中占有的最大 y 坐标 // canvas 只能计较笔墨的宽度,并不能计较出笔墨的高度。以是就操作笔墨的宽度除以笔墨个数计较个或许 var maxY = measure.width / p.name.length + p.y; var min = { x: p.x, y: p.y }; var max = { x: maxX, y: maxY }; // bounds 为该笔墨在 canvas 中所占有的范畴。 // 在取点位坐标作为最小范畴时,textAlign、textBaseline 凭证以下方法配置会较量精确。 // 如配置在差异的位置展示,范畴最大、最小点也需举办调解 // ctx.textAlign = "left"; // ctx.textBaseline = "top"; var bounds = new Bounds(min, max); Bounds 范畴工具 /** * 界说范畴工具 */ 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; }; 检测 // 每次绘制之前先与已绘制的笔墨举办范畴交错检测 // 如发明有交错,则放弃绘制当前笔墨,不然绘制并存入已绘制笔墨列表 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 地点 (编辑:河北网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |