如何从 html canvas 上的 tileset sheet 多次绘制特定的 tileset 而不是整个图像

How to draw a specific tileset from tileset sheet on html canvas multiple times instead of whole image

所以我有一个 tileset,里面装满了小瓷砖,如地面、水、树木等。我有一个 for 循环,它循环特定次数以在 canvas 上绘制瓷砖。它要么像我需要的那样只绘制一次特定的小图块,要么在全屏上绘制整个图像或特定的小图块。但是我需要一些草块在 canvas 上重复 25 次才能生成地图。代码:

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);
  }
}

我在循环中尝试 * 0, j * 0 但没有帮助

现在是这样的:

但我需要它是这样的:

sprite.draw(background, 30, 30, 36, 36, i * 36, j * 36, 36, 36);
  • sprite.width/height 不能在这里发挥作用,因为图块表包含(可能包含)大量图块,而您只想获取(并放置)其中的一小部分
  • 与0的乘法意义不大,我想你已经感觉到了。

(和drawImage如果你需要再看一遍:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage


哦是的。 Loader 这种方式不行,浏览器是异步加载图片的,用那种方法时图片将不可用 returns。

这是您可以进行的快速测试 运行:

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);
//  }
//}

绘图的东西已经被移动到图像加载的事件处理程序中。

旁注:我看到了 console.log(background); 行,可能您正在尝试检查 background 是否是图像。它是,但它是一个空的,它的内容和 width/height 当时不可用。