canvas measureText()
measureText方法可以測量文字的寬度,從其名稱入手有助於理解與記憶。
此方法名稱由如下兩個單詞合成:
(1).measure:翻譯成漢語具有"測量"和"度量"的意思。
(2).text:翻譯成漢語具有"文字"的意思。
語法結構:
[JavaScript] 純文字檢視 複製程式碼context.measureText(text).width;
方法解析:
(1).text:將要被測量的文字。
(2).width:此方法返回一個物件,其width屬性可以返回文字的寬度。
瀏覽器相容:
(1).IE9+瀏覽器支援此方法。
(2).edge瀏覽器支援此方法。
(3).谷歌瀏覽器支援此方法。
(4).火狐瀏覽器支援此方法。
(5).Opera瀏覽器支援此方法。
(6).Safari瀏覽器支援此方法。
程式碼例項如下:
[HTML] 純文字檢視 複製程式碼執行程式碼<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>螞蟻部落</title> <style> canvas{ border:1px solid #d3d3d3; width:300px; height:150px; } </style> <script> window.onload = () => { let cvs=document.getElementById("myCanvas"); let ctx=cvs.getContext("2d"); ctx.font="30px Arial"; let txt="螞蟻部落" ctx.fillText("width:" + ctx.measureText(txt).width,10,50) ctx.fillText(txt,10,100); console.log(ctx.measureText(txt)) } </script> </head> <body> <canvas id="myCanvas">當前瀏覽器canvas標籤</canvas> </body> </html>
程式碼執行效果截圖如下:
程式碼分析如下:
(1).首先繪製一段文字,然後通過measureText()方法去測量文字。
(2).此方法返回一個物件,此物件具有一個width屬性,返回文字的寬度。
相關文章
- canvasCanvas
- canvas clearRect()Canvas
- canvas toBlob()Canvas
- canvas toDataURL()Canvas
- canvas stroke()Canvas
- canvas fill()Canvas
- canvas fillRect()Canvas
- canvas translate()Canvas
- canvas rotate()Canvas
- canvas scale()Canvas
- canvas fillText()Canvas
- canvas createPattern()Canvas
- canvas createImageData()Canvas
- canvas restore()CanvasREST
- canvas save()Canvas
- canvas putImageData()Canvas
- canvas drawImage()Canvas
- canvas clip()Canvas
- canvas arcTo()Canvas
- canvas isPointInPath()Canvas
- canvas arc()Canvas
- canvas getImageData()Canvas
- canvas fillStyleCanvas
- canvas closePath()Canvas
- canvas beginPath()Canvas
- canvas strokeRect()Canvas
- canvas strokeStyleCanvas
- canvas rect()Canvas
- canvas setTransform()CanvasORM
- canvas(三)Canvas
- 初探canvasCanvas
- Canvas 教程Canvas
- canvas transform()CanvasORM
- canvas apiCanvasAPI
- react canvasReactCanvas
- canvas translateCanvas
- One simple way to draw canvas, wxml2canvasCanvasXML
- WPF C# create canvas and draw ellipse in canvasC#Canvas