How to change image size with JavaScript?

Estimated read time 1 min read

There are a few ways to change the size of an image using JavaScript. Here’s one way to do it:

<img id="myImage" src="yourImage.jpg" width="300" height="200">

<script>
  var img = document.getElementById("myImage");
  img.width = 500;
  img.height = 300;
</script>

In this example, we first get a reference to the image element by using document.getElementById("myImage"). Then, we change the width and height properties of the image to resize it. The new values of width and height are set to 500 and 300 respectively.

Note that this will stretch or shrink the image, which may affect its quality. If you want to preserve the aspect ratio of the image, you can calculate the new dimensions based on the original aspect ratio and then set the width and height accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply