Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Make Canvas Responsive to Pixel Ratio

    Phil HoldenPhil 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.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:01 Let's start with a canvas.

    00:06 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.

    00:22 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.

    00:36

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

    00:47 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 image, which is responsive to the device pixel ratio.

    Discuss

    Discuss