149

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 the right is what I want (hand-drawn for illustrative purposes).

Chrome interpolates scaled canvas elements A non-interpolated version

7
  • 1
    Somewhat related, though not identical: stackoverflow.com/questions/195262/… Sep 30, 2011 at 19:24
  • 1
    I believe that question is referring to the line-drawing functions drawing anti-aliased lines. I'm referring to how resized canvas elements are rendered with interpolation by default.
    – namuol
    Sep 30, 2011 at 19:26
  • Yes, sorry...I first thought the questions the same then immediately noticed my mistake. :-/ What if you were to try using the pixelation filter of jsmanipulate? joelb.me/jsmanipulate Sep 30, 2011 at 19:34
  • 1
    That's more of an image-filter meant for photographs.
    – namuol
    Sep 30, 2011 at 19:37
  • Yes, but if it transforms your left image into a good enough version of your right image to make you happy then it could provide a cross-browser solution (considering it's not looking too promising to find a flag for this drawing mode, universal or otherwise, in WebKit). Whether it's a viable substitute depends on the problem you are trying to solve...if you really need discrete pixel drawing or if you're just trying to ensure the result is pixelated with a certain granularity. Sep 30, 2011 at 20:09

6 Answers 6

146

Last Updated: 2014-09-12

Is there a canvas property or browser setting I can change programmatically to disable interpolation when scaling elements?

The answer is maybe some day. For now, you'll have to resort to hack-arounds to get what you want.


image-rendering

The working draft of CSS3 outlines a new property, image-rendering that should do what I want:

The image-rendering property provides a hint to the user-agent about what aspects of an image are most important to preserve when the image is scaled, to aid the user-agent in the choice of an appropriate scaling algorithm.

The specification outlines three accepted values: auto, crisp-edges, and pixelated.

pixelated:

When scaling the image up, the "nearest neighbor" or similar algorithm must be used, so that the image appears to be simply composed of very large pixels. When scaling down, this is the same as auto.

Standard? Cross-browser?

Since this is merely a working draft, there's no guarantee that this will become standard. Browser support is currently spotty, at best.

The Mozilla Developer Network has a pretty thorough page dedicated to the current state of the art which I highly recommend reading.

The Webkit developers initially chose to tentatively implement this as -webkit-optimize-contrast, but Chromium/Chrome don't seem to be using a version of Webkit that implements this.

Update: 2014-09-12

Chrome 38 now supports image-rendering: pixelated!

Firefox has a bug report open to get image-rendering: pixelated implemented, but -moz-crisp-edges works for now.

Solution?

The most cross-platform, CSS-only solution so far is thus:

canvas {
  image-rendering: optimizeSpeed;             /* Older versions of FF          */
  image-rendering: -moz-crisp-edges;          /* FF 6.0+                       */
  image-rendering: -webkit-optimize-contrast; /* Safari                        */
  image-rendering: -o-crisp-edges;            /* OS X & Windows Opera (12.02+) */
  image-rendering: pixelated;                 /* Awesome future-browsers       */
  -ms-interpolation-mode: nearest-neighbor;   /* IE                            */
}

Sadly this wont work on all major HTML5 platforms yet (Chrome, in particular).

Of course, one could manually scale up images using nearest-neighbor interpolation onto high-resolution canvas surfaces in javascript, or even pre-scale images server-side, but in my case this will be forbiddingly costly so it is not a viable option.

ImpactJS uses a texture pre-scaling technique to get around all this FUD. Impact's developer, Dominic Szablewski, wrote a very in-depth article about this (he even ended up citing this question in his research).

See Simon's answer for a canvas-based solution that relies on the imageSmoothingEnabled property (not available in older browsers, but simpler than pre-scaling and pretty widely-supported).

Live Demo

If you'd like to test the CSS properties discussed in the MDN article on canvas elements, I've made this fiddle which should display something like this, blurry or not, depending on your browser: a 4:1 (64x64 to 256x256) image of an isometric pixel-art style TV

6
  • Image-rendering seems to work elsewhere, but webkit browsers. I really hope that Chrome/Chromium/Safari staff reads well what "switch to EPX interpolation in low-load situations" means. When I first read the sentence I thought that optimize-contrast allows new colors created in low load, but NO: en.wikipedia.org/wiki/… Oct 7, 2012 at 20:54
  • 2
    Opera 12.02 on Mac and Windows supports image-rendering:-o-crisp-edges ( jsfiddle.net/VAXrL/21 ), so you could add it on your answer. Oct 8, 2012 at 10:47
  • Is it supposed to work when I'm increasing the browser zoom? I've tested drawing with FF 22, Chrome 27 and IE 10 on Windows 7 when the browser zoom is 150% and the result is blurry on all browsers. When I double the canvas width and height and set it back to the original width and height with CSS it draws sharp lines.
    – pablo
    Jul 9, 2013 at 15:33
  • That's a good question. I'm not sure if there's a spec for user-specified scaling behavior.
    – namuol
    Jul 10, 2013 at 20:19
  • 4
    I’m (from the present future!) on Chrome 78. I’m seeing “image-rendering: pixelated;” working. It looks like this was added in 2015 to Chrome 41: developers.google.com/web/updates/2015/01/pixelated
    – MrColes
    Dec 8, 2019 at 23:47
69

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

7
  • 1
    Unfortunately it looks like this doesn't work yet, either. Maybe I'm missing something? Here's a test: jsfiddle.net/VAXrL/187
    – namuol
    Aug 31, 2012 at 20:43
  • 13
    you have to scale using the canvas API for it to work, you can't scale with CSS ever and have the canvas API affect it! So something like this: jsfiddle.net/VAXrL/190 Aug 31, 2012 at 21:13
  • 1
    But the nature of this problem isn't really about canvas. It's about how the browser renders scaled images, including <canvas> elements.
    – namuol
    Sep 4, 2012 at 2:33
  • 4
    If you scale using CSS, namuol's solution will work. If you scale the image manually onto the Canvas, Simon's solution works. It's neat that there are solutions for both cases, so thanks to you both! Sep 16, 2012 at 16:58
  • For IE 11: msImageSmoothingEnabled works for me! msdn.microsoft.com/en-us/library/dn265062(v=vs.85).aspx
    – steve
    Mar 15, 2016 at 17:28
11

Edit 7/31/2012 - This functionality is now in the canvas spec! See separate answer here:

https://stackoverflow.com/a/11751817/154112

Old answer is below for posterity.


Depending on your desired effect, you have this as one option:

var can = document.getElementById('b');
var ctx = can.getContext('2d');
ctx.scale(5,5);
$('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();
});

http://jsfiddle.net/wa95p/

Which creates this:

enter image description here

Probably not what you want. But if you were merely looking to have zero blur then that would be the ticket so I'll offer it just in case.

A more difficult option is to use pixel manipulation and write an algorithm yourself for the job. Each pixel of the first image becomes a 5x5 block of pixels on the new image. It wouldn't be too hard to do with imagedata.

But Canvas and CSS alone won't help you here for scaling one to the other with the exact effect you desire.

3
  • Yeah, that's what I was afraid of. Apparently, image-rendering: -webkit-optimize-contrast should do the trick but doesn't seem to do anything. I may look into rolling a function to scale up a canvas' contents using nearest-neighbor interpolation.
    – namuol
    Sep 30, 2011 at 21:51
  • I originally accepted your answer; I revoked it for now because there seems to be confusion about whether this is a duplicate or not.
    – namuol
    Oct 3, 2011 at 15:13
  • I have a more complete answer after doing some research and would like to reopen the question to provide my answer.
    – namuol
    Oct 3, 2011 at 15:20
3

In google chrome, canvas image patterns aren't interpolated.

Here is a working example edited from the namuol answer http://jsfiddle.net/pGs4f/

ctx.scale(4, 4);
ctx.fillStyle = ctx.createPattern(image, 'repeat');
ctx.fillRect(0, 0, 64, 64);
5
  • This is the most attractive workaround I've seen so far. Not sure about performance yet, but it's totally worth looking into. I'll try it out.
    – namuol
    May 12, 2012 at 1:58
  • using repeat instead of no-repeat is faster. Don't know why. It's also pretty fast, three.js use this in CanvasRenderer
    – saviski
    Jul 26, 2012 at 20:00
  • 6
    update: no longer works with chrome 21 (due to the retina display support added?) new version jsfiddle.net/saviski/pGs4f/12 using imageSmoothingEnabled pointed by Simon
    – saviski
    Aug 7, 2012 at 23:04
  • When Retina resolution comes general, things changes enormously. When iPhone4-5 style 326dpi (128dpcm) Retina display comes to 24 inch (52x32cm) monitors, the screen size will be 6656 x 4096 px. Then antialiasing is bad, and all browser vendors (even Webkit based) is forced to allow disabling antialiasing. Antialiasing is cpu-intensive operation and antialiasing 6656 x 4096 px image would be too slow, but fortunately unnecessary in such display. Oct 10, 2012 at 15:45
  • 1
    Just as a side-note, here's a good benchmark aboout patterns vs image: jsperf.com/drawimage-vs-canvaspattern/9
    – yckart
    Apr 28, 2013 at 17:21
2

All you have to do is set the image-rendering: pixelated CSS property on the <canvas>. This is now supported by all browsers. (https://caniuse.com/mdn-css_properties_image-rendering_pixelated)

1
  • Namuol's answer is great. But in 2022 you can just set this property and not worry about the history of the feature. Aug 20, 2022 at 17:52
1

Saviski's workaround explicated here is promising, because it works on:

  • Chrome 22.0.1229.79 Mac OS X 10.6.8
  • Chrome 22.0.1229.79 m Windows 7
  • Chromium 18.0.1025.168 (Developer Build 134367 Linux) Ubuntu 11.10
  • Firefox 3.6.25 Windows 7

But not works in the following, but the same effect can be achieved using CSS image-rendering:

  • Firefox 15.0.1 Mac OS X 10.6.8 (image-rendering:-moz-crisp-edges works in this )
  • Opera 12.02 Mac OS X 10.6.8 (image-rendering:-o-crisp-edges works in this )
  • Opera 12.02 Windows 7 (image-rendering:-o-crisp-edges works in this )

The problematic are these, because ctx.XXXImageSmoothingEnabled is not working and image-rendering is not working:

  • Safari 5.1.7 Mac OS X 10.6.8. (image-rendering:-webkit-optimize-contrast NOT works)
  • Safari 5.1.7 Windows 7 (image-rendering:-webkit-optimize-contrast NOT works)
  • IE 9 Windows 7 (-ms-interpolation-mode:nearest-neighbor NOT works)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.