High DPI Canvas: Drawing Sharp Graphics on Retina Displays

HiDPI screens make everything look smoother and cleaner, but they also present a new set of challenges for developers. This article examines the unique difficulties of drawing canvas images in the context of HiDPI displays.

The devicePixelRatio property

Before HiDPI screens existed, a pixel was just a pixel, and setting something to be 100px wide was all there was to it. Then the first HiDPI mobile handsets introduced the somewhat enigmatic devicePixelRatio property on the window object, also available for use in media queries. This property revealed the ratio of how logical pixel values, like those in CSS, translate to the actual number of pixels a device uses for rendering. For example, an iPhone 4S has a devicePixelRatio of 2, so a 100px logical value equates to a 200px device value.

In the early days of these devices, developers noticed images being upscaled and appearing blurry, because they were creating images at the logical pixel width of their elements. When drawn, those images were upscaled by the devicePixelRatio and lost their sharpness.

The de facto solution has been to create images scaled up by the devicePixelRatio and then use CSS to scale them down by the same amount — and the same approach applies to canvas.