Search code examples
javascriptcssgame-development

canvas drawImage pixelated (pixel art)


I am programming a mining game using HTML, CSS, and JavaScript (no external libraries). I am using the drawImage() canvas function to draw individual ore displays onto the canvas. I am attempting to apply the image-rendering style to the image as pixelated. However, the images still appear blurry. Only one image is loaded per ore type. Here is the code where ores are declared:

class Ore {
    constructor(name, /*...*/) {
        // ...
        this.texture = new Image(32, 32)
        this.texture.src = `assets/ores/${name}.png`
        this.texture.onload = () => {loadProg += 1; this.texture.style.imageRendering = "pixelated"}
        // ...
    }
}

Here is the code where the ore is rendered which is ran every frame (ctx is my canvas context):

function render() {
    ctx.clearRect(0, 0, 2000, 920)
    // line below selects all ores visible
    oreDisplays.filter((i) => (i.yOffset == yOffset)).forEach((i) => {
        ctx.drawImage(i.texture, i.pos[0], i.pos[1], 40, 40)
    })
    // ...
}

I have tried doing it both with and without it running with onload and typing the image-rendering style with and without a dash. I have also tried using normal CSS with img. I expected for the images to not be blurry when zoomed in. However, they still are blurry.

Image of ores still rendering blurry

I do not care how messy the solution is as long as it works, does not heavily affect the performance, and does not use any external libraries other than jQuery (only if neccesary).


Solution

  • Use in CSS: image-rendering: pixelated; on the canvas element (not on the img):

    canvas {
      image-rendering: pixelated;
    }
    

    https://developer.mozilla.org/en-US/docs/Games/Techniques/Crisp_pixel_art_look
    If your entire game is pixel art... makes no sense to mix up styles anyway ;)