Select Category - Web Dev

Category: Web Dev

Low-Res Hard Pixel Scaling with HTML5 Canvas and Javascript

canvas scaling gif

Here's just a little bit of code for cleanly scaling a small resolution canvas to a larger one. I threw this together out of excitement for Deviever's Lowrez Jam. However I have way too much of my own Ride the Bullet development going on to try to build a Javascript game from scratch right now.

Anyways the idea is to draw everything to a small canvas and then treat that as an image to be drawn to a canvas of any size.

The code:

I have a 32x32 canvas that is drawn to a 512x512 canvas. The code is really ugly, but the idea is there.

The key lines of code are:

gctx.imageSmoothingEnabled = false;
gctx.webkitImageSmoothingEnabled = false;
gctx.mozImageSmoothingEnabled = false;

These prevent the browser from interpolating between pixels (which gives a blurry look).

Also note that in order for this to work, you can't scale your canvas with CSS. If you take a 32x32 canvas and set it to 512px by 512px in css, you will still end up with the blurry interpolation.

Here is my test project in action:

And a link to all the code and images:

Edit: msImageSmoothingEnabled works on IE11 and apparently some versions of IE10, and oImageSmoothingEnabled should work for some versions of opera though I havn't gotten around to testing any.

Back to top