DLev
DLev

Reputation: 53

html5 canvas: maxWidth argument to fillText produces ugly results in Chrome

The maxWidth argument to fillText can be used to restrict the maximum width the text renders into, however, in chrome I sometimes get very odd results. Here is a particularly bad example where I need to restrict the width of the text by just a couple pixels. Above is a call to fillText with no maxWidth specified. The bottom example has a maxWidth. There is too big a space between the "w" and "a". Are there any tricks or workarounds to get better results?

"Iowa" rendered in chrome and firefox

Here's the code used for the example:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.font="8pt Arial";
ctx.fillText("Iowa", 10, 40);
ctx.fillText("Iowa", 10, 56, 21);

(edit: simpler repro) To repro you can go here and look at the bottom right box.

Update: The original question stated that there was a problem in firefox as well. That was an error. The issue only seems to be present in chrome.

Upvotes: 3

Views: 3573

Answers (1)

Boris Zbarsky
Boris Zbarsky

Reputation: 35064

Your basic problem is that maxWidth performs scaling on the rendered text, but most text doesn't scale very well to non-integer sizes... Basically, if you ask for an 7.9px font things won't fit the pixel grid well and will look ugly.

In terms of avoiding it... apart from using a higher DPI display (not really under your control, I know), there's not that much you can do short of avoiding the API. :(

Upvotes: 1

Related Questions