0

function getRandomInt(min,max) { // random number from (inclusive,exclusive)
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max-min)) + min;
}

var boardLayout = [  // index of images for the canvas
  'redtile.png','bluetile.png','greentile.png','shoptile.png','healthtile.png','trainingtile.png'
  ];
  
imageObj.onload = function(x,y) { // onload function outside the loop
  context.drawImage(imageObj,x,y,x+100,y+100); // makes each image non-overlapping and 100x100
};
  
for (var x = 0; 900 > x; x += 100) { 
  for (var y = 0; 700 > y; y += 100) { // every 100x100 square should have another image on it
    var integer = getRandomInt(0,6);
    var tile = boardLayout[integer]; // gets a random image from boardLayout
    var canvas = document.getElementById('game');
    var context = canvas.getContext('2d');
    var imageObj = new Image();
    image.onload(x,y); // calling my function
    imageObj.src = tile; 
  }
}
<!doctype html>
<html>
    <head>
        <title>Fiona</title>
    </head>
<body>
<canvas id='game' width="900px" height="700px" style="border:2px solid #000000;">
  </canvas>

<script type='text/javascript' src='try.js'></script>
</body>
</html>

I'm pretty new to this, so I was hesitant to post on here, but after a few hours I gave in. The goal is to create a canvas that will have a random assortment of the "boardLayout" images on it. Each image will be 100x100 and the canvas is just big enough for my for-loops, so it should cover the entire canvas.

I have tried countless different ways of doing this over the last few hours and have inserted what I think is the closest I got to doing it. My problem is that I can't put a function (imageObj.onload) into a for-loop and I can't get it to work with the for-loop separate from or even inside the function.

the only thing that pulls up on my html document is the border. I have gotten a picture into the canvas, just never more than one at a time. Any help is appreciated!

johndoe
  • 1
  • 1
  • You need to use `imageObj.onload = function(){ /* call rendering function here*/ }` because you are trying to draw the image before it has loaded. – Blindman67 Aug 25 '16 at 12:22
  • Ditto what @Blindman67 says. Also, by putting `var imageObj=new Image` inside your `for-loop` you are constantly overwriting the previous image that is still trying to load with a `new Image`. Don't reuse `imageObj` in your loop. [Here](http://stackoverflow.com/questions/30578521/how-do-image-preloaders-work/30581295#30581295) is a previous Q&A showing how to preload all your images before trying to load them. – markE Aug 25 '16 at 16:45

0 Answers0