js: Make Canvas Responsive to Pixel Ratio

Datetime:2016-08-23 03:00:57          Topic:          Share

Make Canvas Responsive to Pixel Ratio

1:06 JavaScript lesson byPhil Holden

Canvas is great for high performance graphics rendering but by default the results look blocky on phones tablets and laptops with high pixel density or Retina displays. By using canvas width and height attributes and style props we can use window.devicePixelRatio to create a canvas that is responsive to pixel ratio.

  • Share this lesson:
  • Facebook
  • Twitter
  • Google+

Comment Guidelines

Member comments are a way for PRO Members to communicate, interact, and ask questions about a lesson.

Commenting Guidelines

Here are some basic guidelines for commenting on egghead.io.

Be on-topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contactclick here.

Avoid meta-discussion

Is your comment resembles:

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1

It will likely be deleted as "meta".

Code problem?

Should be accompanied by code! JSFiddle, Plunker, CodePen, etc all provide a way to share code and discuss it in context.

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

egghead.io comment guidelines

egghead.io

Canvas is great for high performance graphics rendering but by default the results look blocky on phones tablets and laptops with high pixel density or Retina displays. By using canvas width and height attributes and style props we can use window.devicePixelRatio to create a canvas that is responsive to pixel ratio.

Let's start with a canvas.

It's much faster to paint graphics to the screen using canvas and DOM. But on high pixel density displays, like phones and Macbooks, the results look pixelated. This is because by default one canvas pixel equals one CSS pixel, not one screen pixel.

To fix this, let's create a scale factor from the device pixel ratio. We use a scale factors to create a canvas, use width and height attributes, so double the CSS pixel width and height sizes we require. We make all our painting calls relative to the scale factor.

[pause]

Finally, we shrink the canvas back down to the size we require, using the style's width attribute.

To recap, the width and height attributes on the canvas element determine the number of pixels in the canvas, while the CSS width and height properties determine the size it will display on the screen. By setting an element's attributes different to the CSS properties, we can create a [inaudible 1:03] image, which is responsive to the device pixel ratio.