Disable Interpolation when Scaling a <canvas>
To disable canvas scaling interpolation, set imageSmoothingEnabled
on the canvas context to false
. This will keep your canvas pixel perfect, even when scaling!
Using CSS3's 'image-rendering' Property
With CSS3, we can dictate how images (including <canvas>
elements) should be scaled. The image-rendering
property has several accepted values, including pixelated
, which instructs the browser to use nearest-neighbor interpolation:
Keep in mind though, like our notorious browser inconsistencies, browser support can vary, so spare yourself the headache and always test across different browsers.
Compatibility with Browsers
Mozilla and Webkit
Browser compatibility is like playing PCR Roulette. Fret not! For Firefox, they've named their kid mozImageSmoothingEnabled
, while Webkit browsers have unsupported-sibling issues and call theirs webkitImageSmoothingEnabled
:
Can I Use?
Before you celebrate, Caniuse.com is a great resource to check if your image-rendering: pixelated
party invite has been accepted by all browsers. Note that the party starts from Chrome 38 onwards.
When JavaScript Comes to the Rescue
Scaling, The Manual Way
JavaScript to the rescue! If you crave absolute control, perform manual scaling, creating a bigger canvas and enlarging all pixels individually.
ImageData - Direct Manipulation
If manipulating canvas seems like fun, say hello to ImageData
object. Here, you can be the puppet master, allowing you to enforce custom pixel-algorithms for scaling.
Best Practices for High Performance Apps
When it comes to 8-Bit retro games or artwork, where performance is crucial, you can use server-side pre-scaling of your images. Say goodbye to lag!
The Power of Patterns
Add variation with ctx.createPattern
, a nifty approach that allows fields to be tiled with images without distortion upon scaling:
Practical Examples
Interactive examples let you see the magic unfold as you manipulate the code. I mean, who doesn't love a good JsFiddle or CodePen?
The scale() Method
With scale()
, drawings will retain their sharpness even after you scale them. Just don't forget to set imageSmoothingEnabled
to false
:
Was this article helpful?