【问题标题】:Canvas' Image type in an Array of Javascript ObjectJavascript 对象数组中的画布图像类型
【发布时间】:2016-06-09 19:10:30
【问题描述】:

下午好, 我的代码需要一些帮助,我正在尝试使用用户可以单击的 Hearts 在画布中编写地图,但我想将这些心形存储到一个数组中以使用 for 循环显示它们。

我的代码在这里:

var canvas = document.getElementById("mapC");
        var ctx = canvas.getContext("2d");

        var Heart = function(link, posX, posY) {
            this.link = link;
            this.posX = posX;
            this.posY = posY;
            this.pic = new Image();
            this.pic.addEventListener("load", function() {
                ctx.drawImage(this.pic, this.posX, this.posY);
            }, false);
            this.pic.src = "heart.png";

        }
        Heart.prototype.heartClick = function()
        {
                document.location.href= this.link;
        }

        var heartsArray = new Array();
        heartsArray.push(new Heart("this", 40, 40));

问题是

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

但是我的“this.pic”图片是可在数组中显示的类型,我没有发现错误,请帮助我。

【问题讨论】:

    标签: javascript arrays html object canvas


    【解决方案1】:

    在你的回调函数this 指向全局对象window。 您应该将this 的引用保存到新变量中,然后您就可以使用它了。

    var self = this;
    this.pic.addEventListener("load", function() {
        ctx.drawImage(self.pic, self.posX, self.posY);
    }, false);
    

    【讨论】:

    • 谢谢你,这是解决方案:)
    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 2013-06-27
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多