Crisp pixel art on a canvas

The canvas smooths scaled sprites too. Turn it off, in two places.

SNP 129 #513 Filed js pixelart gamedev

javascript
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

ctx.imageSmoothingEnabled = false
ctx.drawImage(sprite, 0, 0, 16, 16, x, y, 64, 64)

That handles scaling inside the canvas. If the canvas itself is scaled up by CSS, you also need:

css
canvas {
  image-rendering: pixelated;
  width: 100%;
}

Setting imageSmoothingEnabled resets whenever the canvas is resized, so do it again after changing canvas.width or canvas.height. And draw at whole-number coordinates (Math.round(x)), or sprites land between pixels and blur anyway.