簡體   English   中英

如何更改圖像的寬度和高度 JavaScript

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

我有這段代碼可以在我的網站中添加圖像,但我想調整它的大小

 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>

使用此代碼,我想讓圖像更小

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

出於某種原因,它不起作用。 任何人都知道問題可能是什么?

您可以通過 css class 調整 img 的大小,您可以使用 Z686155AF75A60A0F6EZDEDD80C 為 img 設置 class

您附加了錯誤的元素(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