javascript - 使用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>
解决方案
推荐阅读
- java - 如何使用 Java Panama FFI 访问 MemoryLayout 中的 C_POINTER
- docker - 解析 skaffold 配置:解析 skaffold 配置文件时出错
- curry - 在 Curry 中,如何让逆向函数终止?
- javascript - 如何以一键形式发送事件
- flutter - 如何在音频库中检查音频是否完成?
- javascript - 在 for 循环中等待直到回调完成
- webpack - webpack 模块规则配置中的 `test`、`include`、`resource` 属性有什么区别?
- vue.js - vue js中的动态查询字符串名称
- javascript - 如何使用 JavaScipt 获取重定向链接?
- javascript - 在 promise.then 或 promise.catch 中调用时,Array.push 的工作很奇怪