Skip to content Skip to sidebar Skip to footer

Using Nearest-neighbor With Css Zoom On Canvas (and Img)

When using the CSS zoom property, how can I convince the browser to use 'nearest neighbor', instead of 'bilinear' or any other more advanced zooming algorithms? My setup is a div t

Solution 1:

There is a way. I asked a question similar to this over here: How to stretch images with no antialiasing and got a really good response. I've modified it quite a bit since then, but here's a simple version which stretches (w/out anti-aliasing) when clicked: http://jsfiddle.net/howlermiller/U2eBZ/1/

It's incredibly hackish though. Don't use it unless you must. It has to re-create the image every time you click on it, so with a big image it would be slow and terrible. But it does work on Chrome/Windows.

Edit: This is supported in the CSS3 spec now! Support is super spotty at the moment, but Chrome just added support so I'm hopeful that we'll be able to use it before too long. Good times!

.thing {
  /* IE, only works on <img> tags */
  -ms-interpolation-mode: nearest-neighbor;
  /* Firefox */image-rendering: crisp-edges;
  /* Chromium + Safari */image-rendering: pixelated;
}

Demo

Solution 2:

ctx.webkitImageSmoothingEnabled=false now seems to work since 22.

Solution 3:

Since you're using canvas anyway, you might as well implement your own zoom and manually implement nearest neighbour resizing.

I suspect even if you solve this problem, you'll run into something else one day.

@Timothy's answer seems to have some good code you can use to help with the actual math.

Post a Comment for "Using Nearest-neighbor With Css Zoom On Canvas (and Img)"