Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Poor anti-aliasing of text drawn on Canvas

I'm drawing text on Canvas, and am disappointed with the quality of antialiasing. As far as I've been able to determine, browsers don't do subpixel antialising of text on Canvas.

Is this accurate?

This is particularly noticeable on iPhone and Android, where the resulting text isn't as crisp as text rendered by other DOM elements.

Any suggestions for high quality text out put on Canvas?

Joubert

like image 688
Joubert Nel Avatar asked Mar 10 '11 15:03

Joubert Nel


People also ask

How do I render text in canvas?

To draw text on a canvas, the most important property and methods are: font - defines the font properties for the text. fillText(text,x,y) - draws "filled" text on the canvas. strokeText(text,x,y) - draws text on the canvas (no fill)

Can you use text on canvas?

Visuals make sense, but using text in canvas prints can be a powerful way to make a statement. Text is a strong design choice, especially used cleverly and combined with affordable, high-quality canvas prints.

What is aliased font?

Another way to abbreviate font names is to create a font alias, a shorter name that is used as an alternative to the full font name. Font aliases are specified in a file called fonts.

How do I make text selectable in canvas?

the text drawn in canvas elements cannot be selected, because of the nature of the canvas tag. But there are a few workarounds, like the one used in typefaceJS. Another solution would be to add text with positioned div elements instead of useing strokeText or fillText.


1 Answers

My answer came from this link, maybe it will help someone else. http://www.html5rocks.com/en/tutorials/canvas/hidpi/

The important code is as follows.

// finally query the various pixel ratios
    devicePixelRatio = window.devicePixelRatio || 1,
    backingStoreRatio = context.webkitBackingStorePixelRatio ||
                        context.mozBackingStorePixelRatio ||
                        context.msBackingStorePixelRatio ||
                        context.oBackingStorePixelRatio ||
                        context.backingStorePixelRatio || 1,

    ratio = devicePixelRatio / backingStoreRatio;

// upscale the canvas if the two ratios don't match
if (devicePixelRatio !== backingStoreRatio) {

    var oldWidth = canvas.width;
    var oldHeight = canvas.height;

    canvas.width = oldWidth * ratio;
    canvas.height = oldHeight * ratio;

    canvas.style.width = oldWidth + 'px';
    canvas.style.height = oldHeight + 'px';

    // now scale the context to counter
    // the fact that we've manually scaled
    // our canvas element
    context.scale(ratio, ratio);

}
like image 99
cnotethegr8 Avatar answered Sep 27 '22 21:09

cnotethegr8