Home > Enterprise >  How to change the width and height of an image JavaScript
How to change the width and height of an image JavaScript

Time:08-02

I have this code to add an image in my website but I want to resize it

 var questionHeader = document.getElementById("a");
 var img = new Image(),
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d");

  img.onload = () => {
    let width = Math.floor(img.naturalWidth * 0.1),
      height = Math.floor(img.naturalHeight * 0.1);
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(img, 0, 0, width, height);
  };
  img.src = "https://cdn-icons-png.flaticon.com/512/7951/7951990.png";

  questionHeader.appendChild(img);
<div id="a"></div>

With this code I want to make the image smaller

  let width = Math.floor(img.naturalWidth * 0.1),
      height = Math.floor(img.naturalHeight * 0.1);
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(img, 0, 0, width, height);

For some reason it's not working though. Anyone knows what the problem may be?

CodePudding user response:

You can resize img by css class and you can set class for img with JavaScript by classname

CodePudding user response:

You appended the wrong element (img instead of canvas).

 var questionHeader = document.getElementById("a");
 var img = new Image(),
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d");

  img.onload = () => {
    let width = Math.floor(img.naturalWidth * 0.1),
      height = Math.floor(img.naturalHeight * 0.1);
    canvas.width = width;
    canvas.height = height;
            canvas.style.border   = "1px solid";

    ctx.drawImage(img, 0, 0, width, height);
  };
  img.src = "https://cdn-icons-png.flaticon.com/512/7951/7951990.png";

  questionHeader.appendChild(canvas);
  • Related