美文网首页
canvas遍历插入多张图片

canvas遍历插入多张图片

作者: 关自由 | 来源:发表于2019-03-09 19:55 被阅读0次

想要一次引入多张图片在canvas中,但是onload后 循环中i为数组的最大数。所以只能用IIFE来控制i

<body>

<canvas id="canvas" width="600" height="600" style="border: 1px solid black"></canvas>

<script>

var canvas=document.getElementById("canvas");

var ctx=canvas.getContext("2d");

//图片序号

var arr=[0,1,2]

//存储图片的数组

var Rarr=[];

    //遍历序号,将图片放入Rarr中

for(var i=0;i<arr.length;i++){

(function(i){

var img=new Image();

img.src="images/"+arr[i]+".png";

img.onload=function(){

Rarr.push(this);

//只能在这个地方画图,出了IIFE Rarr数组为空

ctx.drawImage(Rarr[i],100*i,100*i,100,100)

}

}

)(i)

};

</script>

</body>

相关文章

网友评论

      本文标题:canvas遍历插入多张图片

      本文链接:https://www.haomeiwen.com/subject/oxuepqtx.html