简体   繁体   中英

Different font widths in html5-canvas

i have a pretty simple but very annoying problem. I try to read the width of a string in a canvas. I know how to do this, and it works. But the results differ from browser to browser.

ctx.font = "10px Arial";
var txt = "This is a text demonstration. Why is the width of this text different in every browser??";
ctx.fillText("width:" + ctx.measureText(txt).width, 10, 50);
ctx.fillText(txt, 10, 100);

Here a little fiddle: http://jsfiddle.net/83v7c4jv/

Chrome: 390px, IE: 375px, Firefox: 394px. Only IE is accurate, since C# gives me the same result if i try this there. Does anybody know why and how i can get Chrome and Firefox to render and calculate the same values like IE?

you need to read this answer

it worked for me in some project , i used this code to get height of the text because it not exist it will work the same as text width

obj.lineHeight = function(){


                var testDiv = document.createElement('div'); // creating div to measure text in 
                    testDiv.style.padding= "0px";
                    testDiv.style.margin = "0px";
                    testDiv.style.backgroundColor = "white";
                    testDiv.textContent = "Hello World !";
                    testDiv.style.fontSize = obj.size+"px";
                    testDiv.style.fontFamily = obj.fontFamily;
                    testDiv.style.clear = "both";
                    testDiv.style.visibility="hidden";
                    document.body.appendChild(testDiv);
                    var __height__ =  testDiv.clientHeight;
                    testDiv.style.display = "none";
                    document.body.removeChild(testDiv);

                    return __height__ ;

            };

First of all, the same font may be rendered different in different browsers. Pay attention on the following picture. I just putted together screenshots of your JSFIDDLE running on Chrome (the first) and IE (the second). As you can see, the text width actually is not the same, and the numbers that ctx.measureText returns are correct in the both cases.

在此输入图像描述

C# gives you the same number as IE because they use the same text rendering algorithm, but it has no meaning when your page runs on other browser.

You can found some tricks and hacks in this thread , but in fact you cannot really control the browser rendering mechanism. If you want to ensure your text to be shown exactly the same on all the browsers and only way is to turn it into an image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM