Alex Rivera | Logout

Disable Interpolation when Scaling a <canvas>

Asked 2011-09-30T19:14:47.743
151

NOTE: This has to do with how existing canvas elements are rendered when scaled up, not to do with how lines or graphics are rendered onto a canvas surface. In other words, this has everything to do with interpolation of scaled elements, and nothing to do with antialiasing of graphics being drawn on a canvas. I'm not concerned with how the browser draws lines; I care about how the browser renders the canvas element itself when it is scaled up.


Is there a canvas property or browser setting I can change programmatically to disable interpolation when scaling <canvas> elements? A cross-browser solution is ideal but not essential; Webkit-based browsers are my main target. Performance is very important.

This question is most similar but does not illustrate the problem sufficiently. For what it's worth, I have tried image-rendering: -webkit-optimize-contrast to no avail.

The application will be a "retro" 8-bit styled game written in HTML5+JS to make it clear what I need.


To illustrate, here is an example. (live version)

Suppose I have a 21x21 canvas...

<canvas id='b' width='21' height='21'></canvas>

...which has css that makes the element 5 times larger (105x105):

canvas { border: 5px solid #ddd; }
canvas#b { width: 105px; height: 105px; } /* 5 * 21 = 105 */

I draw a simple 'X' on the canvas like so:

$('canvas').each(function () {
    var ctx = this.getContext("2d");
    ctx.moveTo(0,0);
    ctx.lineTo(21,21);
    ctx.moveTo(0,21);
    ctx.lineTo(21,0);
    ctx.stroke();
});

The image on the left is what Chromium (14.0) renders. The image on t

Edit
Report

1 Answer

70

New answer 7/31/2012

This is finally in the canvas spec!

The specification has recently added a property called imageSmoothingEnabled, which defaults to true and determines if images drawn on non-integer coordinates or drawn scaled will use a smoother algorithm. If it is set to false then nearest-neighbor is used, producing a less smooth image and instead just making larger looking pixels.

Image smoothing has only recently been added to the canvas specification and isn’t supported by all browsers, but some browsers have implemented vendor-prefixed versions of this property. On the context there exists mozImageSmoothingEnabled in Firefox and webkitImageSmoothingEnabled in Chrome and Safari, and setting these to false will stop anti-aliasing from occurring. Unfortunately, at the time of writing, IE9 and Opera have not implemented this property, vendor prefixed or otherwise.


Preview: JSFiddle

Result:

enter image description here

answered 2012-08-01T02:32:38.183

Your Answer