Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas drawing and Retina display: doable?

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?

like image 468
DA. Avatar asked Jan 18 '11 03:01

DA.


3 Answers

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 + "px";
    canvas.style.height = canvasHeight + "px";

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

Full code on gist, demo on jsfiddle

like image 116
Joubert Nel Avatar answered Oct 15 '22 12:10

Joubert Nel


There is a drop-in polyfill that will take care of most basic drawing operations for you, and remove the ambiguity between browsers that handle this automatically for you (safari) and others that don't.

https://github.com/jondavidjohn/hidpi-canvas-polyfill

You simply include it before your drawing code and it should give you decent retina support automatically.

like image 3
jondavidjohn Avatar answered Oct 15 '22 11:10

jondavidjohn


I couldn't find anywhere else on the internet suggesting this so I figured it out. If you have a full screen canvas and you want it to be the actual amount of pixels that the device has, just remove this line from your HTML:

<meta name='viewport' content='width=device-width' />

Don't set the viewport at all. Then you just do:

canvas.width = innerWidth
canvas.height = innerHeight
canvas.style.width = innerWidth+'px'
canvas.style.height = innerHeight+'px'

That will use the full screen resolution of the device. A pixel will always be a pixel. You don't need to scale. And getImageData() will give the same values that you see.

like image 1
Curtis Avatar answered Oct 15 '22 13:10

Curtis