189 8069 5689

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

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

创新互联建站服务项目包括永新网站建设、永新网站制作、永新网页制作以及永新网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,永新网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到永新省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

创建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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


本文名称:在小程序Canvas中使用measureText的方法示例
标题链接:http://cdxtjz.cn/article/jpdejh.html

其他资讯