Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView w/ HTML5 Canvas & Retina Display

My app has a UIWebView that serves up local content. If I take a retina size image and use it as a background for the body, I can make it scale properly using the CSS -webkit-background-size property. This gives me a crisp, clear image on the iPhone 4.

The HTML5 Canvas tag isn't so cooperative, however. When I use the drawImage command to place the same retina size image into an HTML5 canvas, it's gigantic -- well past the bounds of the physical screen. This is the code I'm using:

ctx.drawImage(retinaImage, 0, 0)

If I try placing height and width parameters on the drawImage, the picture scales down to fit the screen, but it's blocky and pixelated. Not crisp like the CSS background.

Is there a trick I can use for the HTML5 Canvas that is equivalent to the CSS -webkit-background-size property?

Thanks!

Update:

Here's the final code I used to solve this problem. Hopefully it helps someone else in the future:

        if (window.devicePixelRatio == 2) {
            myCanvas.setAttribute('height', window.innerHeight * 2);
            myCanvas.setAttribute('width', window.innerWidth * 2);
            ctx.scale(2, 2);
        } else {
            myCanvas.setAttribute('height', window.innerHeight);
            myCanvas.setAttribute('width', window.innerWidth);
        }
like image 470
Axeva Avatar asked Oct 14 '22 19:10

Axeva


1 Answers

Check out http://joubert.posterous.com/crisp-html-5-canvas-text-on-mobile-phones-and. Looks like if you multiple the dimensions by the devicePixelRatio then scale by that ratio as well it should work.

Here's some pseudo-code that worked for me.

var ctx = myCanvasElem.getContext("2d");
ctx.attr("width", width * window.devicePixelRatio);
ctx.attr("height", height * window.devicePixelRatio);
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
ctx.drawImage(img, x, y, width, height);

Let me know if that solves it for you!

like image 182
Rob Barreca Avatar answered Oct 25 '22 03:10

Rob Barreca