Poor anti-aliasing of text drawn on Canvas

Joubert Nel picture Joubert Nel · Mar 10, 2011 · Viewed 13.4k times · Source

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

Answer

cnotethegr8 picture cnotethegr8 · Oct 2, 2014

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);

}