Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to execute 'drawImage' on 'CanvasRenderingContext2D

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)' at drawCanvas (userscript.html?id=0e769594-f15d-490f-a75c-bac819525aab:56) at setTimeout (userscript.html?id=0e769594-f15d-490f-a75c-bac819525aab:59)

I am trying to load images to a canvas based on url input, i've tried adding event listeners and a logger, none seem to work.

setTimeout(() => {

    let startpanel = document.getElementById('startpanel')

    // image for skin
    var img = document.createElement("img");
    img.style.width = "220px";
    img.style.height = "177px";

    // input custom skin
    var skinInput = document.createElement("input");
    skinInput.placeholder = "skin url";
    skinInput.style.width = "150px";
    skinInput.style.height = "35px";

    skinInput.onblur = function() {
        const newImage = new Image();
        newImage.src = skinInput.value;
        img.src = skinInput.value;
        drawCanvas(newImage);
      };

    startpanel.appendChild(skinInput)

    // draw skin
    var appearance = document.createElement("canvas");
    appearance.id = "appearance";
    // appearance.style.position = "absolute";
    appearance.style.top = "100px";
    appearance.style.width = "200px";
    appearance.style.height = "177px";
    appearance.style.border = "1px solid #d3d3d3";
    startpanel.appendChild(appearance)

    const drawCanvas = (newImage) => {
        var ctx = appearance.getContext("2d");
        ctx.drawImage(newImage, 10, 10);
      }

      drawCanvas();

}, 3000);
like image 671
BernardJones Avatar asked Mar 18 '26 00:03

BernardJones


2 Answers

I think this error is thrown because you call your own function "drawCanvas(newImage)" without argument after define it : "drawCanvas()".

So, your function call the context function drawImage with a null first argument : "ctx.drawImage(newImage, 10, 10)"

If you remove the line "drawCanvas()" the error is not thrown.

like image 174
Florian Callewaert Avatar answered Mar 19 '26 14:03

Florian Callewaert


Make sure the image arugment passed to drawImage() method is not broken. Check its src if pointing to valid image source.

like image 44
Pratap Singh Avatar answered Mar 19 '26 14:03

Pratap Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!