溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Canvas怎么實現(xiàn)文字碰撞檢測并抽稀

發(fā)布時間:2021-05-08 17:13:15 來源:億速云 閱讀:167 作者:Leah 欄目:web開發(fā)

使用Canvas怎么實現(xiàn)文字碰撞檢測并抽???針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

計算文字在 canvas 中所占據(jù)的范圍

// 計算文字所需的寬度
var p = {
  x: 10,
  y: 10,
  name: "測試文字"
};
var measure = ctx.measureText(p.name);
// 求出文字在 canvas 畫板中占據(jù)的最大 y 坐標
var maxX = measure.width + p.x;
// 求出文字在 canvas 畫板中占據(jù)的最大 y 坐標
// canvas 只能計算文字的寬度,并不能計算出文字的高度。所以就利用文字的寬度除以文字個數(shù)計算個大概
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 中所占據(jù)的范圍。
// 在取點位坐標作為最小范圍時,textAlign、textBaseline 按照以下方式設置會比較準確。
// 如設置在不同的位置展示,范圍最大、最小點也需進行調(diào)整
// 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;
};

檢測

// 每次繪制之前先與已繪制的文字進行范圍交叉檢測
// 如發(fā)現(xiàn)有交叉,則放棄繪制當前文字,否則繪制并存入已繪制文字列表
for (var index in _textBounds) {
  // 循環(huán)所有已繪制的文字范圍,檢測是否和當前文字范圍有交集,如果有交集說明會碰撞,則跳過該文字
  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);

關于使用Canvas怎么實現(xiàn)文字碰撞檢測并抽稀問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI