在小程序Canvas中使用measureText的方法示例
有時(shí)候我們在使用Canvas繪制一段文本時(shí),會(huì)需要通過measureText()方法獲取文本的寬度,例如:
創(chuàng)建canvas標(biāo)簽
<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返回的其實(shí)是一個(gè)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,所以我自己寫了個(gè)類似于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í)有所幫助,也希望大家多多支持腳本之家。
- js canvas實(shí)現(xiàn)寫字動(dòng)畫效果
- JS+HTML5 Canvas實(shí)現(xiàn)簡單的寫字板功能示例
- js+html5實(shí)現(xiàn)canvas繪制鏤空字體文本的方法
- Javascript保存網(wǎng)頁為圖片借助于html2canvas庫實(shí)現(xiàn)
- javascript結(jié)合html5 canvas實(shí)現(xiàn)(可調(diào)畫筆顏色/粗細(xì)/橡皮)的涂鴉板
- JavaScript+html5 canvas實(shí)現(xiàn)本地截圖教程
- html5 canvas js(數(shù)字時(shí)鐘)實(shí)例代碼
- JS+Canvas 實(shí)現(xiàn)下雨下雪效果
- js使用html2canvas實(shí)現(xiàn)屏幕截取的示例代碼
- JS使用canvas中的measureText方法測量字體寬度示例
相關(guān)文章
一些常用的JS功能函數(shù)(2009-06-04更新)
將 ClientMentInfo類改成了兼容IE6,IE7,IE8,Vista,Windows 7和Firefox2009-06-06ECMAScript6輪播圖實(shí)踐知識總結(jié)
最近萌生了用ECMAScript6寫一個(gè)輪播圖的想法,以前就知道ECMAScript6,但是一直沒有學(xué),現(xiàn)在終于下決心學(xué)了,本篇文章會(huì)總結(jié)在實(shí)踐中用到的ES6的知識。2016-08-08swiper4實(shí)現(xiàn)移動(dòng)端導(dǎo)航切換
這篇文章主要為大家詳細(xì)介紹了swiper4實(shí)現(xiàn)移動(dòng)端導(dǎo)航切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09hash特點(diǎn)、hashchange事件介紹及其常見應(yīng)用場景
淺析hash特點(diǎn)、hashchange事件介紹及其常見應(yīng)用場景(不同hash對應(yīng)不同事件處理、移動(dòng)端大圖展示狀態(tài)后退頁面問題、原生輕應(yīng)用頭部后退問題、移動(dòng)端自帶返回按鈕二次確認(rèn)問題),hashchange和popstate事件觸發(fā)條件2023-11-11