通常在作地圖相關的需求是纔會用到文字抽稀,我也是在爲公司的地圖引擎實現一個功能時才實現了該方法,在這裏將其簡化了,就在普通的 Canvas 上進行操做,並無引入地圖概念html
// 計算文字所需的寬度 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 範圍對象git
/** * 定義範圍對象 */ 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 地址github
閱讀原文