Search code examples
javascriptcanvas

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

Solution

  • 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.