我正在学习 Javascript 和 Canvas。在这种情况下请帮助我。我想用几个冒号绘制一行图像,最后一个总是覆盖前一个。
示例如下:
function main(){
contains Canvas creating
canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
and init();
}
//Row 是我的构造函数,带有坐标和 drawImage 方法。 DrawImage 接受图像数组;
function Row(x,y){
var _this = this;
_this.x = x;
_this.y = y;
this.drawImage = function(img2){
img.onload = function(){
for(var i = 0; i < img2.length; i+=1){
ctx.drawImage(img2[i], _this.x, this.y + i * canvas.height / 4, canvas.width / 5, canvas.height / 4);
console.log(_this.x);
};
};
};
};
//例如,我创建两行并设置它们不同的坐标。我希望它们位于 Canvas 的不同侧面; var 首先 = 新行(0, 0); var 第二 = 新行(350, 0);
function init(){
loadImage(imgArray);
// IMG is the arrays with images links
// New instances takes the different coordinates, but the last is overwriting the previous. Why?
first.drawImage(IMG);
second.drawImage(IMG);
};
最佳答案
当您调用first.drawImage
时,这会设置img.onload
处理程序。当您调用 Second.drawImage 时,这会覆盖 img.onload 处理程序。尝试使用 img.addEventListener('load', ...)
来代替,以便调用两个回调。
关于javascript - 为什么图像会被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228051/