0
votes

So I have a tileset full of small tiles like ground, water, trees etc. I have a for loop which loops certain times to draw the tile on the canvas. It draws but either only once a small specific tile like I need, or draws the whole image or small specific tile but on the full screen. But I need pieces of grass tile to repeat for 25 times on the canvas to produce a map for instance. The code:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var StyleSheet = function(image, width, height) {
  this.image = image;
  this.width = width;
  this.height = height;


  this.draw = function(image, sx, sy, swidth, sheight, x, y, width, height) {
    image.onload = function() {
      context.drawImage(image, sx, sy, swidth, sheight,x, y, width, height);
    }
  }
}

var Loader = function(src) {
  this.image = new Image();
  this.image.src = src;
  return this.image;
}

var background = new Loader("ground.png");
console.log(background);
var sprite = new StyleSheet(background, 16, 16);
for (i = 0; i < 25; i++) {
  for (j = 0; j < 25; j++) {
    sprite.draw(background, 30, 30, 36, 36, i * 0, j * 0, sprite.width, sprite.height);
  }
}

I try * 0, j * 0 in the loop but doesn;t help

Now it's like this: enter image description here

but I need it to be like this:

enter image description here

1

1 Answers

1
votes
sprite.draw(background, 30, 30, 36, 36, i * 36, j * 36, 36, 36);
  • sprite.width/height can not have a role here as the tilesheet contains (may contain) a large selection of tiles and you want to get (and put) a small part of it only
  • multiplication with 0 doe not make much sense, I think you have felt it already.

(and drawImage if you need to look at it again: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage)


Loader

Here is a quick test you can run:

var Loader = function(src) {
  this.image = new Image();
  this.image.src = src;

  this.image.onload=function(){
    var sprite = new StyleSheet(background, 16, 16);
    for (i = 0; i < 25; i++) {
      for (j = 0; j < 25; j++) {
        sprite.draw(background, 30, 30, 36, 36, i * 0, j * 0, sprite.width, sprite.height);
      }
    }
  }

  return this.image;
}

var background = new Loader("ground.png");
console.log(background);
//var sprite = new StyleSheet(background, 16, 16);
//for (i = 0; i < 25; i++) {
//  for (j = 0; j < 25; j++) {
//    sprite.draw(background, 30, 30, 36, 36, i * 0, j * 0, sprite.width, sprite.height);
//  }
//}

The drawing things have been moved into the event handler of image getting loaded.

Side note: I see the console.log(background); line, proably you were trying to check if background was an image. It was, but it was an empty one, its contents and width/height were not available that time.