HTML5 Canvas:为什么用measureText和offsetWidth()测量文本给出不同的值? [英] HTML5 Canvas: Why does measuring text with measureText and offsetWidth() give different values?

查看:498
本文介绍了HTML5 Canvas:为什么用measureText和offsetWidth()测量文本给出不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基准化offsetWidth()vs measureText,我得到了非常不同的值。他们不应该是一样的吗?为什么它们不同?

I benchmarked offsetWidth() vs measureText and I am getting drastically different values. Shouldn't they be the same? Why are they different?

以下是jsfiddle和原始代码:
http://jsfiddle.net/WhGk7/2/

Here is the jsfiddle and raw code below: 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>


推荐答案

context.measureText 在大多数浏览器中都很糟糕。但是有一个黑客,它允许你得到一个更好的文本测量。使用 visibility:hidden 在HTML文档中创建< div> 节点不 display:none (因此占用空间)。然后将其样式设置为要用于 context.fillText 的相同样式(请记住,当您使用外部字体时,该字体必须完全加载才能获得准确的测量),将您的文本放入div,并检查div的 .width

The support for context.measureText is very bad in most browsers. But there is a hack which allows you to get a much better measurement of text. Create a <div> node in your HTML document with visibility: hidden (so it isn't rendered) but not display: none (so it takes up space). Then set its style to the same style you want to use for context.fillText (remember that when you use an external font, that font must be fully loaded to get an accurate measurement), put your text into the div, and check the div's .width

这篇关于HTML5 Canvas:为什么用measureText和offsetWidth()测量文本给出不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆