带有图像的画布 drawImage() 不绘制任何内容

时间:2021-04-13 17:31:53

标签: javascript html5-canvas

我想将文档的所有图像 src 更改为 dataURL。

我试图通过 for of 循环在画布中绘制所有图像,但它不起作用。 帮帮我!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img src="./adudio1.png" alt=""height="300px"width="200px"class="i">
    <img src="./adudio1.png" alt=""height="300px"width="500px"class="i">

    
</body>
<script>
    const img = document.querySelectorAll("img");
    for(items of img){
        let c = document.createElement("canvas");
        document.querySelector("body").append(c);
        c.height=items.height;
        c.width=items.width;
        c.style="border:2px solid #CCC;";
        ctx = c.getContext("2d");
        ctx.drawImage(items,0,0)
  
    }
</script>
</html>

1 个答案:

答案 0 :(得分:0)

您的代码不会等待图像加载。将您的画布绘图代码添加到每个图像的 onload 函数中,以便仅在图像数据到达时执行它。

const images = document.querySelectorAll("img");

for (const image of images) {
  image.onerror = function () { 
    console.error("image failed to load"); 
  };
  image.onload = function () {
    const canvas = document.createElement("canvas");
    document.body.appendChild(canvas);
    canvas.height = image.height;
    canvas.width = image.width;
    canvas.style = "border: 2px solid #CCC;";
    ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0);
  };
}
<img src="http://placekitten.com/200/300" 
     alt=""
     height="300"
     width="200" 
     class="i"
>
<img src="http://placekitten.com/200/300" 
     alt=""
     height="300"
     width="200" 
     class="i"
>

顺便说一句,height="300px"width="500px" 需要在属性之间使用空格,并且不需要在每个值之后使用 px

使用 const item 而不是 items 以避免在循环中创建全局。