在P5.js中合并图像

我正在 p5.js 上制作游戏,我想合并每个组件的图像以获得游戏的背景,但使用 createGraphics 不起作用。这是代码:

createGameMapImg() {
    let gameImg = createGraphics(this.width * this.boxSize, this.height * this.boxSize);

    gameImg.background(color('white'));

    for (let component of this.components) {
        image(component.img, component.x * this.boxSize, component.y * this.boxSize, component.width * this.boxSize, component.height * this.boxSize);
        if (component.img != undefined) gameImg.image(component.img, component.x * this.boxSize, component.y * this.boxSize, component.width * this.boxSize, component.height * this.boxSize);
    }

    return gameImg;
}

编辑

阅读我的代码几个小时后,我终于明白发生了什么:

  1. 我有一个包含所有组件定义的 JSON(包括 URL img)
  2. 我将此 JSON 发送到管理组件渲染的类。
  3. 我在预加载时调用构造函数,但组件图像不会加载 ulless 我这样做:
this.componetsJSON = loadJSON(componetsJSON, () => this.components = this.createComponets());

这个想法是在加载 JSON 之后,方法 createComponents 加载不同的图像。

回答

如果您的代码有问题,从您发布的极小部分中看不出问题。最有可能的问题在于您如何加载图像或使用结果p5.Graphics实例。这是一个工作示例,我用一个简单的用例填充了空白:

const boxSize = 1;
let components;
let gameMap;

function preload() {
  // We need to load images in preload to make sure they are available when we're drawing them
  let tree = loadImage('https://www.paulwheeler.us/files/tree.png');
  components = [{
      img: loadImage('https://www.paulwheeler.us/files/game_map.png'),
      x: 0,
      y: 0,
      width: 200,
      height: 200
    },
    {
      img: tree,
      x: 20,
      y: 100,
      width: 56,
      height: 70
    },
    {
      img: tree,
      x: 120,
      y: 20,
      width: 56,
      height: 70
    }
  ];
}

function setup() {
  createCanvas(windowWidth, windowHeight);
  gameMap = createGameMapImg();
}

function draw() {
  let size = min(width, height);
  image(gameMap, 0, 0);
}

function createGameMapImg() {
  let gameImg = createGraphics(width * boxSize, height * boxSize);

  gameImg.background(color('white'));

  for (let component of components) {
    // I'm not sure why this was in your code, since it looked
    // like the goal was to draw the images to the cameImg 
    // graphics object:
    // image(component.img, component.x * boxSize, component.y * boxSize, component.width * boxSize, component.height * boxSize);
    if (component.img != undefined) {
      gameImg.image(
        component.img,
        component.x * boxSize,
        component.y * boxSize,
        component.width * boxSize,
        component.height * boxSize
      );
    }
  }

  return gameImg;
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.1/lib/p5.js"></script>


以上是在P5.js中合并图像的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>