0

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?

2
  • You are appending the original image to your document, and not the canvas element that you actually drew the resized image onto. Commented Aug 1, 2022 at 10:43
  • 1
    And by the way wasn’t better to just create an img element? Commented Aug 1, 2022 at 10:44

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.