vmkk6a
Last Updated: February 25, 2016
·
23.57K
· eallam
Ericprofilenew

How to make the canvas not look like crap on retina

This might save you an hour wondering why in the world does the canvas look fuzzy!?!

First, make your canvas element twice as large as you want it, but set it's width and height styles to the target size. For example, if you want a canvas element to be 500 points wide by 375 points high, you would do this:

canvas = document.getElementById('output')
canvas.width = 1000;
canvas.height = 750;
canvas.style.width = "500px";
canvas.style.height = "375px";

If you look at your canvas now, it will look very tiny (half the size to be exact). That's because the canvas drawing context is drawing at normal scale and retina is double that. So you just have to scale the drawing context by 2 times:

canvas.getContext('2d').scale(2,2)

BOOM. Pretty canvas.

Say Thanks
Respond

6 Responses
Add your response

3879
947a2faecf137aea69aeaa9b6e725b23

Thanks, this is great timing. I just had noticed how crappy animation looked on retina for a recent project of mine.

To save anyone else the trouble, note that

context = canvas.getContext('2d').scale(2,2);

will lead to an undefined context. To prevent that, the code should look more like

context = canvas.getContext('2d')
context.scale(2,2)
over 1 year ago ·
4612

Thanks. It was very useful. Now my canvas looks like one on iPad :)

over 1 year ago ·
4613
Transparent large

Be careful: without a slight tweak, this approach is making your canvas slightly blurrier for non-retina users, and making them do much more computation than necessary!

Rather than hard coding the 2x size increase, read the multiplier from window.devicePixelRatio (default to 1 if undefined).

Boom, now you support every resolution and DPI.

over 1 year ago ·
4634

@nevir Thanks!

over 1 year ago ·
10362
221d1bf66f6a590d0fb55c1f76e1b5cf normal

This is a drop in polyfill to make "auto" retina consistent across all browsers (not just safari), no need to modify your canvas source, just drop this in before running your canvas code.

https://github.com/jondavidjohn/hidpi-canvas-polyfill

over 1 year ago ·
17017
F49e4fbf9e689f3741791d38998d1590

Life.. saved. Thanks dude.

over 1 year ago ·