Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
帆布';Javascript对象数组中的图像类型_Javascript_Arrays_Html_Object_Canvas - Fatal编程技术网

帆布';Javascript对象数组中的图像类型

帆布';Javascript对象数组中的图像类型,javascript,arrays,html,object,canvas,Javascript,Arrays,Html,Object,Canvas,下午好, 我需要一些代码方面的帮助,我正在尝试在画布中编写一个地图,其中包含用户可以单击的红心,但我想将这些红心存储到一个数组中,以使用for循环显示它们 我的代码在这里: var canvas = document.getElementById("mapC"); var ctx = canvas.getContext("2d"); var Heart = function(link, posX, posY) { this.link =

下午好, 我需要一些代码方面的帮助,我正在尝试在画布中编写一个地图,其中包含用户可以单击的红心,但我想将这些红心存储到一个数组中,以使用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”图像是可在数组中显示的类型,我找不到错误,请帮助我。

在回调函数
中,此
指向全局对象
窗口
。 您应该将此的引用保存到新变量中,然后才能使用它

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

谢谢,这就是解决方案:)