我需要在自己的画布上绘制图像。我究竟做错了什么? 如果我删除" for循环"代码工作得很好(例如:set var i = 0,然后在canv [0]中绘制img [0]。)
window.onload = function() {
var canv = [];
var ctx = [];
var img = [];
var info = [{"url":"1.jpg"},{"url":"2.jpg"},{"url":"3.jpg"}];
for(i=0; i< 3; i++){
canv[i] = document.createElement('canvas');
canv[i].width = 460;
canv[i].height = 620;
canv[i].style.border = "1px solid";
document.body.appendChild(canv[i]);
img[i] = new Image();
img[i].src = info[i].url;
ctx[i] = canv[i].getContext("2d");
img[i].onload = function(){
ctx[i].drawImage(img[i], 10, 70, 440,440);
}
}
}
答案 0 :(得分:0)
找到解决方案,以防有人遇到同样的问题:
(function (_i) {
img[_i] = new Image();
img[_i].src = info[_i].url;
img[_i].onload = function () {
ctx[_i].drawImage(img[_i], 10, 70, 440,440);
};
})(i);