Categories
JavaScript Answers

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 the canvas context drawImage method.

For instance, we write

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

to call drawImage with the img image, the img image width and height, and the canvas width and height to scale the img image into the canvas width and height.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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