javascript - Javascript 对象数组中的 Canvas 图像类型

标签 javascript arrays html object canvas

下午好, 我的代码需要一些帮助,我正在尝试用用户可以点击的 Hearts 在 Canvas 中编写 map ,但我想将这些心形存入数组以使用 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”图片是数组中可显示的类型,我没有发现错误,请帮助我。

最佳答案

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

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

关于javascript - Javascript 对象数组中的 Canvas 图像类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35653926/

相关文章:

javascript - 如何使用 JSON 列出带有链接的维基百科页面标题?

javascript - 如何用不是原始类型的正确类型覆盖 valueOf()?

javascript - 为什么这段 JavaScript 代码给我错误 "undefined"?

arrays - MiniZinc - (多维)数组的数组

c - 按升序将一维数组输入二维数组 (C)

php - 将关联数组转换为普通数组

javascript - HTML/JavaScript : Timer/Stopwatch doesn't reset (after stop)

jquery - 溢出 Div 中的偏移量问题

javascript - 为什么这个 javascript 会刷新内存泄漏?

javascript - 多个可拖动标记未更新