溫馨提示×

溫馨提示×

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

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

在小程序Canvas中使用measureText的方法示例

發(fā)布時間:2020-10-13 19:26:13 來源:腳本之家 閱讀:195 作者:4fun 欄目:web開發(fā)

有時候我們在使用Canvas繪制一段文本時,會需要通過measureText()方法獲取文本的寬度,例如:

創(chuàng)建canvas標簽

<canvas id="canvas"></canvas>

獲取一段文本的寬度

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var text = ctx.measureText('foo'); // TextMetrics object
text.width; // 16;

如上所示,measureText返回的其實是一個TextMetrics對象,它包含了文本的寬度,MDN上的解釋如下:

The CanvasRenderingContext2D.measureText() method returns a TextMetrics object that contains information about the measured text (such as its width for example).

在微信小程序現(xiàn)在的版本(v2.13.7)中,小程序的canvas還不支持measureText,所以我自己寫了個類似于measureText方法,通過canvas獲取文本的寬度,方法如下:

function measureText (text, fontSize=10) {
  text = String(text);
  var text = text.split('');
  var width = 0;
  text.forEach(function(item) {
    if (/[a-zA-Z]/.test(item)) {
      width += 7;
    } else if (/[0-9]/.test(item)) {
      width += 5.5;
    } else if (/\./.test(item)) {
      width += 2.7;
    } else if (/-/.test(item)) {
      width += 3.25;
    } else if (/[\u4e00-\u9fa5]/.test(item)) { //中文匹配
      width += 10;
    } else if (/\(|\)/.test(item)) {
      width += 3.73;
    } else if (/\s/.test(item)) {
      width += 2.5;
    } else if (/%/.test(item)) {
      width += 8;
    } else {
      width += 10;
    }
  });
  return width * fontSize / 10;
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

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

AI