javascriptimagehtml5-canvasonload

Alter image after loading using html canvas


I want to draw a border around an image after it is loaded using new Image()

This works, I see the border, but modifying image.src inside the onload function calls onload again in an infinite loop. But how can I alter the image otherwise?

let image = new Image();
image.onload = function () {
    console.log("onload");
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    ctx.drawImage(image, 0, 0);
    ctx.strokeStyle = 'red';
    ctx.lineWidth = 5;
    ctx.strokeRect(0, 0, image.width, image.height);
    image.src = canvas.toDataURL();
};
image.src = "https://placehold.co/600x400";
document.body.appendChild(image);


Solution

  • You apply the canvas value to the same <image>, so the onLoad will run again, going into an infinite loop.

    I'd use a temporary image to load the src and then in the onLoad apply it to your actual image element

    let tmpImage = new Image();
    tmpImage.setAttribute('crossorigin', 'anonymous')
    tmpImage.onload = function () {
        console.log("onload");
        let canvas = document.createElement('canvas');
        canvas.width = tmpImage.width;
        canvas.height = tmpImage.height;
        
        let ctx = canvas.getContext('2d');
        ctx.drawImage(tmpImage, 0, 0);
        ctx.strokeStyle = 'red';
        ctx.lineWidth = 5;
        ctx.strokeRect(0, 0, tmpImage.width, tmpImage.height);
        
        let image = new Image();
        image.src = canvas.toDataURL();
        document.body.appendChild(image);
    };
    tmpImage.src = "https://placehold.co/600x400";