我按照j08691 here为canvas提供的代码。
它工作得很好,我尝试了五个canvas元素,但是因为我在JavaScript初学者的帮助,我在JavaScript中遇到错误。
var icon =new Array("icon1","icon2","icon3","icon4","icon5");
var c = new Array();
var ctx = new Array(5);
var img = new Array(5);
var imgsrc = new Array("imgsrc1","imgsrc2","imgsrc3","imgsrc4","imgsrc5");
$(document).ready(function()
{
var i=0;
for (i=0;i<5;i++)
{
c[i]=document.getElementById(icon[i]);
ctx[i]=c[i].getContext("2d");
ctx[i].shadowOffsetX = 12;
ctx[i].shadowOffsetY = 4;
ctx[i].shadowBlur = 5;
ctx[i].shadowColor = '#666';
img[i] = new Image();
img[i].onload = function(i){
ctx[i].drawImage(img[i], 0, 0); //getting error here as "ctx[i] undefined"
};
img[i].src =imgsrc[i];
}
});
HTML
<canvas id="icon1" width="185" height="130" >
<canvas id="icon2" width="185" height="130" >
<canvas id="icon3" width="185" height="130" >
<canvas id="icon4" width="185" height="130" >
<canvas id="icon5" width="185" height="130" >
答案 0 :(得分:1)
@ Nickolay和@apsillers的解释都是正确的,但是它们的代码不起作用,因为它们重新定义了i
/ ctxi
参数,这个参数从未被赋值。请改用以下内容:
function getHandler(i) {
return function() {
ctx[i].drawImage(img[i], 0, 0);
};
}
img[i].onload = getHandler(i);
答案 1 :(得分:0)
ctx [i]和img [i]超出了onload处理程序的范围。
img [[i]但是可以通过这个访问,但你应该将ctx [i]作为你的onload处理程序的参数传递
img[i].onload = function(ctxi) {
return function(ctxi) {
ctxi.drawImage(this, 0, 0);
}
}(ctx[i]);