Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Firefox render canvas text the same as CSS text

I've been experimenting with the canvas tag and Javascript. I've made a page that takes Tweets from the Twitter public timeline and animates them into view. It works by using a canvas element in the background for the animation. When the animation is complete, it creates a div element with the same text over the top. I do this so that the tweet text is selectable and links are clickable.

Now, in Safari, Chrome and even Opera, the canvas text and div text look almost exactly the same. Yet in Firefox, the size of the text is different enough to make it 'jump' at the point it changes into the div.

Does anyone know how to make Firefox render the text the same on the canvas element and the div using CSS? Or is this a rendering inconsistency with the engine.

I have put the page on my website if you want to see what I mean.

Now for the code:

The CSS I'm using for rendering the div contains:

line-height: 21px; font-weight: 100; font-family: Georgia, "New Century Schoolbook", "Nimbus Roman No9 L", serif; font-size: 20px;

For rendering on the canvas I'm using:

this.context.font = this.scale + 'px Georgia';
this.context.fillStyle = "white";
this.context.strokeStyle = 'white';
this.context.fillText(this.text, 0, 0);
this.context.strokeText(this.text, 0, 0);

where this.scale is an animated scale factor that finishes at 20px exactly. So, to recap, I'm using the same font and ending up at the same px size, yet Firefox renders the text differently between Canvas and CSS.

(edit) Here's a screenshot example: alt text http://danforys.com/temp/firefox-behaviour.png

First line is the text animating in using canvas, second line is the resulting div.

like image 721
Dan Forys Avatar asked May 04 '10 06:05

Dan Forys


1 Answers

Right, I have a test case.

I created a div and canvas element side by side with the same text. Turns out that the font rendering was a red herring. What differs with Firefox is the reporting of the character widths. My Twitter visualiser calculates the width of each character using measureText().width and places them accordingly. For some reason, the widths of the characters on Firefox are smaller.

Oddly, in the test case I measure two things:

  1. The total width of the entire text
  2. The sum of the widths of each character in the text

In Chrome, they both come out at 399px. In Firefox, the first comes out as 393px, the second at 367px.

Edit: The bug has been closed. Mozilla say it's invalid, I still say it's inconsistent with the other browsers. I'll have to find another way to do this, or enough info to convince Mozilla that it's a bug after all. Thanks for listening anyway!

like image 92
Dan Forys Avatar answered Oct 17 '22 05:10

Dan Forys