Draw Sharp Scaled Images on Canvas
To draw images on canvas, we can use the Canvas 2D API drawImage()
; sometimes we draw the original image, while at other times we draw scaled images. However, if upscaled images are drawn without some configuration on the canvas context, it may get blurry.
Under the hood, when upscaled images are drawn on canvas, smoothing is enabled if imageSmoothingEnabled
of the canvas rendering context is set to true (which is default). Though this kind of smoothing often makes images blurry…
If we want upscaled images to be sharp, set imageSmoothingEnabled
to false.
The following is a demo that shows drawing upscaled (x1.5 original size) PNG images with smoothing enabled (the first one) and disabled (the second one).
imageSmoothingEnabled
is supported by browsers supporting canvas, as imageSmoothingEnabled
without prefix for Chrome >= 30, but under a prefix for IE & Edge (msImageSmoothingEnabled
), Firefox (mozImageSmoothingEnabled
) and Chrome < 30 (webkitImageSmoothingEnabled
).
It's spec'ed in WHATWG HTML Living Standard.
In the spec, we may also find that there is another property imageSmoothingQuality
which controls the preferred quality of image smoothing. Unfortunatelly, it gains no browser support as of now.