vmkk6a
Last Updated: September 18, 2018
·
32.75K
· eallam

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.

6 Responses
Add your response

3879

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

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

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

Life.. saved. Thanks dude.

over 1 year ago ·