javascript - Trying to get a random image from array, get all the same instead -
im trying render tilebased map on canvas, array of 0s , 1s different images here how create array:
var map = []; function randomimagearray(){ var length = x * y; var arraylength = 0; while(arraylength < length){ var randomimg = math.floor(math.random() * 2) * 1; if(randomimg == 0){ //maparray.push('0'); map.push(0); arraylength += 1; } else { // maparray.push('1'); map.push(1); arraylength += 1; } } }
and how read it, , draw images it
function drawbackground(){ alert(map.tostring()); alert(map.length); for(var tilex = 0; tilex < x; tilex ++) { for(var tiley = 0; tiley < y; tiley++) { for(var p = 0; p < map.length; p++){ if(map[p] === 0){ ctx.drawimage(image, tilex * tilesize,tiley * tilesize , tilesize, tilesize); } else if(map[p] === 1) { ctx.drawimage(image2, tilex * tilesize,tiley * tilesize , tilesize, tilesize); } } } } } my alerts pop out array filled 1s , 0s, , length of 300 on canvas either map total of image1's or image2's
there logic problem in drawbackground() function. looping through whole map every iteration of outer loops, , image gets displayed 1 indicated lastly value in map. seek this:
function drawbackground() { var tilex, tiley, imageidx; (tilex = 0; tilex < x; tilex ++) { (tiley = 0; tiley < y; tiley++) { imageidx = map[tilex * tiley]; if (imageidx === 0) { ctx.drawimage(image, tilex * tilesize,tiley * tilesize , tilesize, tilesize); } else if (imageidx === 1) { ctx.drawimage(image2, tilex * tilesize,tiley * tilesize , tilesize, tilesize); } } } } you can clean farther referencing images array, , using map values index it:
var images = [image, image2]; function drawbackground() { var tilex, tiley; (tilex = 0; tilex < x; tilex ++) { (tiley = 0; tiley < y; tiley++) { ctx.drawimage(images[map[tilex * tiley]], tilex * tilesize, tiley * tilesize, tilesize, tilesize); } } } javascript arrays canvas map
No comments:
Post a Comment