jquery - My Javascript tile map will not draw? -
here script, can't seem figure out what's wrong, want draw tile map 12*12 , tiles 32px - 32px. tiles dont draw when run page, ive tried using parse int shown below still, didn't work.
if(parseint(maparray[x][y]) == 0){ ctx.drawimage(rocktile, posx, posy, tilesize, tilesize); }
here script have created.
var canvas = document.createelement("canvas"); var ctx = canvas.getcontext("2d"); canvas.width = (32 * 12); canvas.height = (32 * 12); document.body.appendchild(canvas); var rocktile = new image(); rocktile.src = "../images/dc-dngn/floor/rect_gray0.png"; var tilesize = 32; var posx = 0; var posy = 0; var maparray = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]; $(document).ready(function(){ drawmap(); }); function drawmap(){ for(var x = 0; x < maparray.length; x++){ for(var y = 0; y < maparray[x].length; y++){ if(maparray[x][y] == 0){ ctx.drawimage(rocktile, posx, posy, tilesize, tilesize); } posx += 32; } posx = 0; posy += 32; } }
if can help me tiles draw appreciated, give thanks you!
you have 2 main problems can see:
you accessingdocument.body
before defined. you using image perchance before loaded. here code solves both these problems:
// variables defined global variables var posx = 0; var posy = 0; var tilesize = 32; var maparray; var canvas; var ctx; var rocktile; $(function() { // document should defined canvas = document.createelement("canvas"); ctx = canvas.getcontext("2d"); canvas.width = (32 * 12); canvas.height = (32 * 12); document.body.appendchild(canvas); maparray = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ]; // wait until image loaded draw rocktile = new image(); rocktile.onload = drawmap; rocktile.src = "../images/dc-dngn/floor/rect_gray0.png"; }); function drawmap(){ posx = 0; posy = 0; for(var x = 0; x < maparray.length; x++){ for(var y = 0; y < maparray[x].length; y++){ if(maparray[x][y] == 0){ ctx.drawimage(rocktile, posx, posy, tilesize, tilesize); } posx += 32; } posx = 0; posy += 32; } }
also sure double check image path.
javascript jquery html5 tiles
No comments:
Post a Comment