How to scale an image to fit on canvas with JavaScript?

Spread the love

Sometimes, we want to scale an image to fit on canvas with JavaScript.

In this article, we’ll look at how to scale an image to fit on canvas with JavaScript.

How to scale an image to fit on canvas with JavaScript?

To scale an image to fit on canvas with JavaScript, we call drawImage.

For instance, we write

ctx.drawImage(
  img,
  0,
  0,
  img.width,
  img.height,
  0,
  0,
  canvas.width,
  canvas.height
);

to call drawImage to the img image with img.width and img.height, which are the image’s original width and height.

Then we pass in canvas.width and canvas.height to scale it to the canvas height.

Conclusion

To scale an image to fit on canvas with JavaScript, we call drawImage.

Leave a Reply

Your email address will not be published. Required fields are marked *