【问题标题】:Uncaught TypeError when calling drawImage function调用drawImage函数时未捕获TypeError
【发布时间】:2019-12-28 07:06:35
【问题描述】:

你好!

我正在尝试在 ReactJS 下使用 canvas 元素。调用 drawImage() 时出现错误。除了 drawImage().. 之外的所有东西都可以工作?

未捕获的类型错误:无法在“CanvasRenderingContext2D”上执行“drawImage”:提供的值不是类型“(HTMLImageElement 或 HTMLVideoElement 或 HTMLCanvasElement 或 ImageBitmap)”

var Canvas = React.createClass({
    componentDidUpdate: function() {
        console.log("componentDidUpdate");
    },

    componentDidMount: function() {
        var context = this.getDOMNode().getContext('2d');
        this.paint(context);
    },

    paint: function(context) {
        context.save();
        context.fillStyle = '#F00';
        context.fillRect(0, 0, 400, 400);
        context.drawImage("image.jpg", 0, 0);
        context.restore();
    },

    render: function(){
        return <canvas width={400} height={400} />;
    }
});

【问题讨论】:

    标签: javascript canvas reactjs


    【解决方案1】:

    你确定在你调用drawImage()之前已经加载了image.jpg吗?

    来自w3schools

    注意:您不能在图像加载之前调用 drawImage() 方法。为确保图像已加载,您可以从 window.onload() 或 document.getElementById("imageID").onload 调用 drawImage()。

    【讨论】:

    • 似乎是一个合理的解决方案。不要让迫在眉睫的 W3S 仇恨者让您失望。 ;-)
    【解决方案2】:

    这发生在我身上。

    我无意中做了drawImage(x, y, img);,当它应该是drawImage(img, x, y); 检查以确保您的参数顺序正确

    在我这样做之后,它仍然没有工作。我正在使用Promises.all()(来自这个答案:https://stackoverflow.com/a/53290838/2336212)并且没有意识到result 是所有传入值的数组。我错误地通过了resolve(images)。我没有收到图像数组,而是收到了图像数组。确保您仅将单个对象通过resolve() 传回,除非您需要一个 2D 数组。我将其更改为 resolve(image) 并且有效。

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 2022-01-07
      • 1970-01-01
      相关资源
      最近更新 更多