skip to Main Content

The canvas takes up all the available space on the screen, I use it to render the background of the site.

        canvas {
            position: absolute;
            width:100%;
            height:100%;
            image-rendering: pixelated;
        }

And I’m drawing images through ctx.drawImage(img, 0,0), I need it to remain its original size based on it’s native resolution, no matter what size the canvas itself is.

I tried to do something with the canvas scaling itself, but it didn’t work.

2

Answers


  1. Chosen as BEST ANSWER

    The problem was setting the canvas size in css

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    

    Is the right way to set canvas size without stretching or shrinking.


  2. It looks like you need to specify the width and height of the image when drawing it like you are. You can do this by providing the width and height as parameters:

     ctx.drawImage(img, 0,0, imageWidth, imageHeight)
    

    the documentation has: drawImage(image, dx, dy, dWidth, dHeight)

    You can look at the image file properties to determine its dimensions

    MDN Documentation – drawImage

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search