Canvas drawing and Retina display: doable?

DA. picture DA. · Jan 18, 2011 · Viewed 16.2k times · Source

Working with phoneGap implementing drawing with Canvas. The catch we've run into is that canvas expects specific pixel dimensions. This is fine except that the iPhone 4's Retina display, from a CSS/Webkit POV is still 320px wide, even though technically there are 640 actual screen pixels.

Is there anyway to accommodate the retina display using Canvas on Webkit while preserving compatibility with non-retina displays?

Answer

Joubert Nel picture Joubert Nel · Mar 15, 2011

I sat with the same problem last week and discovered how to solve it -

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

if (window.devicePixelRatio > 1) {
    var canvasWidth = canvas.width;
    var canvasHeight = canvas.height;

    canvas.width = canvasWidth * window.devicePixelRatio;
    canvas.height = canvasHeight * window.devicePixelRatio;
    canvas.style.width = canvasWidth;
    canvas.style.height = canvasHeight;

    ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
}

Full code on gist, demo on jsfiddle