ISHAAN PATEL
ISHAAN PATEL

Reputation: 161

HTML Canvas: Why Is my image on the canvas so blurry?

I am making a grid for a pathfinding visualizer, and I am concerned that my image icon is very low resolution in the grid cell. I am not sure if this is supposed to be like this due to the small size of the image, but I thought I would ask why it is so blurry and if there is a way to fix it?

Original Image

Image on canvas grid(low res)

This is my css for the canvas:

#myCanvas{

    margin-left: auto;
    margin-right: auto;
    display: block;
    border: 1px solid #000000;

    position: absolute;
    top: 60%;
    transform: translate(0, -50%);  
    left: 0;
    right: 0;

    width : pixelWidth * devicePixelRatio;
    height: pixelHeight * devicePixelRatio;

    transform: translate(0.5, 0.5);
}

This is the canvas in the html:

<canvas id="myCanvas" width="1235" height="520">
</canvas>

Upvotes: 2

Views: 2028

Answers (1)

Bagel03
Bagel03

Reputation: 715

Default context width and height are 300 and 150 respectively. This means that your canvas (no matter how large) is a 300 * 150 image, which blurs your smaller image a lot.

Try:

const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
context.canvas.height = innerHeight; //or your desired height 
context.canvas.width = innerWidth;// or your desired width
context.canvas.style.imageRendering = 'auto';//default

Upvotes: 3

Related Questions