即使图像路径发生变化,Javascript代码也会绘制相同的图像

时间:2015-11-10 12:25:33

标签: javascript image canvas html5-canvas

我目前遇到的问题是,如果我尝试绘制2个不同的图像,它会绘制两次相同的图像。所有这些代码都在循环中发生(这可能是个问题吗?)。调用要绘制的图像的代码是:

    drawImage(imageData.background, 0, 0, 2048, 1918, 0, 0, 2048, 1918);
    drawImage(currentData.player.image, 0, 0, 32, 32, 30, 30, 32, 32);

我的drawImage函数如下:

    function drawImage(whatIMG, spriteX, spriteY, sizeX, sizeY, posX, posY, x, y) {
        drawCanvasImage = new Image();
        drawCanvasImage.src = whatIMG;
        drawCanvasImage.onload = function(){
          ctx.drawImage(drawCanvasImage, spriteX, spriteY, sizeX, sizeY, posX, posY, x, y);
        }
    };

因此尽管imageData.background和currentData.player.image完全不同,但只提到最后一个图像链接是画布上绘制的图像。 This is what it looks like

我的直觉告诉我,我可能需要以某种方式清除'drawCanvasImage'加载图像后的对象,虽然我不确定,因为每次函数完成后都应删除它(?)。

感谢任何帮助,谢谢:)

1 个答案:

答案 0 :(得分:1)

在javascript中,当您不使用单词var来声明变量时,您的变量会隐含全局。

当你这样做时

function drawImage(whatIMG, spriteX, spriteY, sizeX, sizeY, posX, posY, x, y) {
    drawCanvasImage = new Image();
    drawCanvasImage.src = whatIMG;
    ...
}

该函数将在同一drawCanvasImage上执行。特别是,如果连续两次调用此函数,drawCanvasImage将在调用onload函数之前快速更改。执行结果如下所示:

drawCanvasImage = new Image();
drawCanvasImage.src = imageData.background;

drawCanvasImage = new Image();
drawCanvasImage.src = currentData.player.image;

// After the thing is loaded
ctx.drawImage(drawCanvasImage, ...); // params the first call... maybe
ctx.drawImage(drawCanvasImage, ...); // params of the other one

也许写这样的功能可以解决你的问题:

function drawImage(whatIMG, spriteX, spriteY, sizeX, sizeY, posX, posY, x, y) {
    // use var keyword so drawCanvasImage is scoped in this function
    // when you will call this function again,
    // a different drawCanvasImage will be used
    var drawCanvasImage = new Image(); 
    drawCanvasImage.src = whatIMG;
    drawCanvasImage.onload = function(){
      ctx.drawImage(drawCanvasImage, spriteX, spriteY, sizeX, sizeY, posX, posY, x, y);
    }
};