Algorithm to draw sprites on infinite map

Viewed 165

I'm making a game on HTML5 canvas(It's infinite), and I want to make bushes in my game randomly from Perlin noise. I want chunks to be a 16 by 16 grid of tiles, and every tile is 85 pixels away from each other. I just draw the grid with this simple code:

ctx.lineWidth=4,ctx.strokeStyle="#000",ctx.globalAlpha=.06,ctx.beginPath();
for(var p=-5;p<canvas.width;p+=85){ctx.moveTo(p + (offset[0] % 85),0),ctx.lineTo(p + (offset[0] % 85),canvas.height)};
for(var m=-5;m<canvas.height;m+=85){ctx.moveTo(0,m + (offset[1] % 85)),ctx.lineTo(canvas.width,m + (offset[1] % 85))};
ctx.stroke();
ctx.globalAlpha=1;

here's the current code I have for bushes, but I don't know how to make it actually work:

for(x=offset[0];x<offset[0]+16;x++) {
        for(y=offset[1];y<offset[1]+16;y++) {
            if (noise.perlin2(x / 10, y/10) < -0.6) {
              ctx.drawImage(treeimage,  x, y)
            }
        }
    }

I have access to the current chunk of the player, and the offset of objects based on the player's current position (just adding and subtracting to/from it when the player presses an arrow key).

EDIT: Sorry, I didn't explain this correctly. The images show, I can't figure out how to make the bushes have the correct position on the screen when the player moves around, and/or make the 8 chunks around the player also load, but only show when stuff is on the screen.

Just an example:

Before I move just a bit: enter image description here

After I move just a bit: enter image description here

1 Answers

Before you call

ctx.drawImage(treeimage,  x, y)

You must make sure that image is retrieved from server.

One way to do it is insert a little IMG tag on page and later retrieve image from it

<img id="treeimage" src="images/mapobjects/tree2.png" style="display:none;">

window.onload = function() { //use onload if you create drawing at page load 
var treeimage = document.getElementById("treeimage");
ctx.drawImage(treeimage, x, y);
}

Another way is to create IMG tag by code and never display it but ensure it has onload function. After its called since now you can use your image anytime.

window.treeimage = document.createElement('img'); //make it global or take care about scope
treeimage.src = "images/mapobjects/tree2.png";

treeimage.onload = function(){
  //only from now you can use that image
  ctx.drawImage(treeimage, x, y);
};
Related