我对 offsetWidth() 与 measureText 进行了基准测试,我得到了截然不同的值。他们不应该是一样的吗?为什么它们不同?
下面是 jsfiddle 和原始代码:http: //jsfiddle.net/WhGk7/2/
<canvas id="myCanvas" width="300" height="200" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<span id="visibilityHack" style="visibility: hidden; font: 15px Arial;">textAlign=start</span>
<div id="results"></div>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// Create a red line in position 150
ctx.strokeStyle="red";
ctx.moveTo(150,20);
ctx.lineTo(150,170);
ctx.stroke();
var measureTextWidth = ctx.measureText("textAlign=start").width;
var measureTextNode = document.createTextNode("measureTextWidth: " + measureTextWidth);
document.getElementById("results").appendChild(measureTextNode);
var swidth = document.getElementById("visibilityHack").offsetWidth;
var textnode = document.createTextNode(" offsetWidth: " + swidth);
document.getElementById("results").appendChild(textnode);
ctx.font="15px Arial";
// Show the different textAlign values
ctx.textAlign="start";
ctx.fillText("textAlign=start",117,60);
ctx.textAlign="center";
ctx.fillText("textAlign=start",150,120);
</script>