无法在“ CanvasRenderingContext2D”上执行“ drawImage”

时间:2018-12-31 09:02:11

标签: javascript canvas

  

未捕获的TypeError:无法在'CanvasRenderingContext2D'上执行'drawImage':提供的值不是'(CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)类型的值       在drawCanvas(userscript.html?id = 0e769594-f15d-490f-a75c-bac819525aab:56)       在setTimeout(userscript.html?id = 0e769594-f15d-490f-a75c-bac819525aab:59)

我正在尝试根据url输入将图像加载到画布上,我尝试添加事件监听器和记录器,但似乎都无法正常工作。

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

2 个答案:

答案 0 :(得分:0)

我认为引发此错误是因为您在定义了“ drawCanvas()” 后不带参数的情况下调用了自己的函数“ drawCanvas(newImage)”

因此,您的函数使用第一个空参数调用上下文函数 drawImage “ ctx.drawImage(newImage,10,10)”

如果删除行“ drawCanvas()” ,则不会引发错误。

答案 1 :(得分:0)

确保传递给drawImage()方法的图像标记没有损坏。如果指向有效的图像源,请检查其src。