如何将多个图像添加到html5画布 [英] How to add multiple images to html5 canvas
本文介绍了如何将多个图像添加到html5画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将多个图像添加到 Html5 canvas ,但是每次我尝试删除最后一个图像并显示最近的图像时,它都会失败.这是我的代码:
I am trying to add multiple images to Html5 canvas but every time I try to remove the last image and show the most recent one it fails. Here's my code:
var imgArray = ['abc.png','455.jpg'];
for(i = 0; i < 2; i++){
var canvas = document.getElementById('canvas');
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = imgArray[i];
imageObj.onload = function() {
context.drawImage(this,0,0);
};
}
如果我运行此代码,它将在画布上显示第二张图像,并删除第一张图像.有什么办法可以保留这两个图像吗?
If I run this code, it shows the 2nd image on the canvas and removes the first one. Is there any way to retain both the images?
推荐答案
实际上,onLoad始终使用变量的 last 值.因此,在之前中存储(计算)img x,y坐标.像这样:
Actually onLoad always uses last value of the variables. So store (calculate) img x, y coordinates before. Smth like this:
imageObj.setAtX = i * 10;
imageObj.setAtY = i * 10;
imageObj.onload = function() {
context.drawImage(this, this.setAtX, this.setAtY);
};
这篇关于如何将多个图像添加到html5画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文