Canvas image scale 2x w/o anti-alias in Chrome

/ Published in: JavaScript
Save to your folder(s)

Somewhere along the road the people behind canvas decided that all image scaling is anti-aliased by default. Firefox has 'mozImageSmoothingEnabled' while Chrome et company don't.

This is a proof of concept script to resize 'virtualCanvas' two times and draw it on 'targetCanvas' w/o any antialiasing.

Proof of concept in that it still takes too long to compute in real time.
- Firefox: 1ms with native antialiasing off
- Chrome: 45ms with the script below

It might be useful to use this to scale assets before doing any compositioning. Like, load images, scale them up, position everything times two... But if yer planning to composite the canvas first and scale that to fit as the last step, I'd advice against it..

Copy this code and paste it in your HTML
  1. var targetContext = targetCanvas.getContext("2d")
  2. var h, w, hV = virtualCanvas.height, wV = virtualCanvas.width, h2, w2
  4. for (h = 0; h < hV; h++) {
  5. h2 = h * 2
  6. for (w = 0; w < wV; w++) {
  7. w2 = w * 2
  8. targetContext.drawImage( this.virtualCanvas, w, h, 1, 1, w2, h2, 2, 2 )
  9. }
  10. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.