开发者

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);开发者_如何学Go
            ctx.scale(2, 2);
        } else {
            myCanvas.setAttribute('height', window.innerHeight);
            myCanvas.setAttribute('width', window.innerWidth);
        }


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜