I recently re-wrote my favorite zApp Demotivate to use HTML5’s Canvas to scale and crop images taken by the iDevice’s camera. I’m a bit dyslexic when it comes to numbers, so trying to keep track of all the corners while accounting for the various screen sizes and orientations was a tad frustrating, but rewarding once I figured it out.
After I got everything working in the iPhone simulator, I tried it for the first time on my iPhone 4. Crap! Everything was messed up. I did not think to account for the Retina display! This added a few new kinks in equation, but once I really understood how Apple implemented the Retina display, it began to make sense.
The standard iPhone screen is 360 pixels by 480 pixels. The retina screen is 640×960, but Apple got all funky and instead of adding more pixels, they made these sub-pixels to cram more dots in the same amount of space. The thing to understand here is that every two of these sub-pixels makes a normal pixel. So if you try to display a 360×480 image on the screen of a Retina iPhone, it will take up the entire screen. The only way to take advantage of the sub-pixels is to force the image to squish into a smaller space. Think about that for a minute while we look at this code.
var canvas = document.getElementById('pic');
canvas.width = 640;
canvas.height = 960;
canvas.style.width = "320px";
canvas.style.height = "480px";
The above code renders perfectly on a Retina display! Why? Because we are using the larger canvas, then squishing it into a smaller space with CSS. Once you understand this, it is pretty easy to take advantage of the beautiful Retina display. And when you forget, well Apple will just render everything normally for you, which doesn’t look half bad on the tiny little phone anyways.