Trying to convert 18 png images to an ‘animation’ of 18 canvases/contexts. code is self explanatory, i see the png on screen when i don’t use an array (version that is commented out). i don’t see a png when i try to use an array (non commented out version). i have snake0 to 17 .png in same folder as thiscode.html. so the problem is… that… uh… I’d like to see a png on the screen when using an array. Cuz that would be… cool.
i see the red 60x30 fill but it doesnt show png on screen as pasted with an array of canvases/contexts. if u comment out oppositely (single canvas, no array) it does show png on screen.
<!DOCTYPE html>
<title>png problem</title>
<meta charset="utf-8"/>
<canvas id="canvas" width="700" height="550" oncontextmenu="return false"></canvas>
<script>
function main(){
if (paused==false){
ctx.fillStyle='rgb(128,128,128)'
ctx.fillRect(0,0,canvas.width,canvas.height)
ctx2.fillStyle='rgb(255,255,255)'
ctx2.fillRect(0,0,canvas2.width,canvas2.height)
ctx2.drawImage(snakecans[1],0,0) //does not work with array (comment out the opposite line and block below when testing)
//ctx2.drawImage(snakecan,0,0) //does work (no array)
ctx.drawImage(canvas2,0,0,canvas2.width,canvas2.height, 5,5,canvas2.width,canvas2.height)
}
}
canvas=document.getElementById('canvas')
ctx=canvas.getContext('2d')
canvas2=document.createElement('canvas')
canvas2.width=540
canvas2.height=540
ctx2=canvas2.getContext('2d')
//does not work (comment out opposite block and line above when testing)
//can't see any png on screen
//i have 18 pngs. i want to put them in 18 'canvases' (so i guess i need 18 contexts too)
snakecans=[]
snakectxs=[]
var i=0
for(i=0;i<18;i++){
snakecans.push(document.createElement('canvas'))
snakecans[i].width=60
snakecans[i].height=30
snakectxs.push(snakecans[i].getContext('2d'))
im=new Image()
im.src='snake'+String(i)+'.png'
im.onload=function(i,snakectxs){ //you apparently need this onload or the png wont load in time
console.log(i)
snakectxs[i].fillStyle='rgb(255,0,0)'
snakectxs[i].fillRect(0,0,snakecans[i].width,snakecans[i].height)
snakectxs[i].drawImage(im,0,0)
}(i,snakectxs) //says 'snakectxs[i] is undefined' unless I put that stuff in parentheses
}
//does work
//can see png on screen
/*
snakecan=document.createElement('canvas')
snakecan.width=60
snakecan.height=30
snakectx=snakecan.getContext('2d')
im=new Image()
im.src='snake'+String(3)+'.png'
im.onload=function(){
snakectx.drawImage(im,0,0)
}
*/
paused=false
setInterval(main, 1000/60)
</script>