Skip to content
Advertisement

Canvas drawImage() with image doesn’t draw anything

I want to change all images src of document to dataURL.

I am trying to draw all image in canvas through for of loop but it doesn’t work. Help me!

<!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>

Advertisement

Answer

Your code isn’t waiting for the images to load. Add your canvas drawing code to the onload function of each image to execute it only once the image data arrives.

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"
>

As an aside, height="300px"width="500px" needs spaces between properties and doesn’t need px after each value.

Use const item rather than items to avoid creating a global in your loop.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement