首页 > 解决方案 > 使用javascript在画布上选择身体的右侧

问题描述

嗨,我正在尝试在画布主体上选择一个非常特定的部分来生成该范围内的元素。让我更好地解释一下:

我把画布(所以身体)分成两部分,在左边我放了一个元素:

this.x1 = Math.floor(Math.random() * ((this.width / 2) - 50) + 50);

this.width整个屏幕的长度在哪里。(我还限制了 50px 以避免屏幕边框)。

所以第一个元素产生在画布的左侧,我需要对第二个元素(x2)做同样的事情,但在屏幕的右侧。

我无法找到解决方案。

我在这里留下了一部分代码,有什么想法吗?

class Mapping {
  constructor() {
    this.colors = ["purple", "red", "yellow", "green"];
    this.canvas = document.getElementById("game");
    this.ctx = this.canvas.getContext("2d");
    this.width = window.innerWidth;
    this.height = window.innerHeight;
  }

  start() {
    this.canvas.width = this.width;
    this.canvas.height = this.height;
  }

  generation() {
    this.ctx.fillStyle = "green";
    this.ctx.fillRect(0, (this.height - 50), this.width, 50); //floor
  }
}

class Tank1 extends Mapping {
  constructor() {
    super();
    this.x1 = Math.floor(Math.random() * ((this.width / 2) - 50) + 50);
    this.y = 100;
  }
  colorPlayer1() {
    return this.colors[0];
  }

  tank() {
    this.ctx.fillStyle = this.colorPlayer1();
    this.ctx.fillRect(this.x1, this.y, 45, 35);
  }
}

class Tank2 extends Mapping {
  constructor() {
    super();
    this.x2 = 500;
//i would like to put this element on the left side with the same rules of the first element
    this.y = 100;
  }

  colorPlayer2() {
    return this.colors[1];
  }

  tank() {
    this.ctx.fillStyle = this.colorPlayer2();
    this.ctx.fillRect(this.x2, this.y, 45, 35);
  }
}

let map = new Mapping();
let player1 = new Tank1();
let player2 = new Tank2();

map.start();
map.generation()

player1.tank();
player2.tank();
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
}

#game {
  display: block;
}
<body>
  <canvas id="game"></canvas>
  <script src="src/script.js"></script>
</body>

标签: javascriptcanvas

解决方案


推荐阅读