当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 在小程序Canvas中使用measureText的方法示例

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

2018年11月03日  | 移动技术网IT编程  | 我要评论
有时候我们在使用canvas绘制一段文本时,会需要通过measuretext()方法获取文本的宽度,例如: 创建canvas标签 <canvas id

有时候我们在使用canvas绘制一段文本时,会需要通过measuretext()方法获取文本的宽度,例如:

创建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).

在微信小程序现在的版本(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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网