源码:
<!DOCTYPE html> <!-- Author:苏一恒 Date:2019/10/11 11:41 Motto: The best time to plant trees is ten years ago, followed by now. 种树最好的时间是十年前,其次是现在。 --> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>度量文本MeasureText</title> <style> body { background: #eeeeee; } #canvas { background: #ffffff; margin-top: 5px; margin-left: 10px; -webkit-box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.5); -moz-box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.5); box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.5); border: 1px solid rgba(0, 0, 0, 0.2); } </style> </head> <body> <canvas id='canvas'>canvas not supports</canvas> <p>width展示的是在Canvas画布上的字符串'Hello'的宽度</p> <script> 'use strict'; let canvas = document.getElementById('canvas'), context = canvas.getContext('2d'); context.font = '24px Arial'; let word = 'Hello'; context.fillText(word, 10, 50); context.fillText('width:' + context.measureText(word).width, 10, 100); </script> </body> </html>