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.
Written by Eric Allam
Related protips
7 Responses
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)
Thanks. It was very useful. Now my canvas looks like one on iPad :)
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.
@nevir Thanks!
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.
Life.. saved. Thanks dude.
you can use https://github.com/cburgmer/rasterizeHTML.js instead of html2canvas