简体   繁体   English

如何更改图像的宽度和高度 JavaScript

[英]How to change the width and height of an image JavaScript

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?任何人都知道问题可能是什么?

You can resize img by css class and you can set class for img with JavaScript by classname您可以通过 css class 调整 img 的大小,您可以使用 Z686155AF75A60A0F6EZDEDD80C 为 img 设置 class

You appended the wrong element (img instead of canvas).您附加了错误的元素(img 而不是 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM