如何使用JavaScript在Canvas画布右侧区域按规则生成元素
解决方案:在Canvas右侧区域生成符合边界规则的随机元素
嘿,这问题其实很简单,你只需要调整随机位置的计算公式,让第二个坦克落在屏幕的右侧区域,同时保持和左侧一样的“不超出边框”规则就行!
核心思路
左侧区域的x范围是 50px 到 屏幕宽度的一半 - 50px,那右侧区域对应的范围应该是 屏幕宽度的一半 到 屏幕总宽度 - 50px。我们只需要把随机数的起始偏移量从50改成屏幕宽度的一半,随机范围保持和左侧一致。
修改后的关键代码
只需要修改Tank2类的x2赋值,替换原来的固定值:
class Tank2 extends Mapping { constructor() { super(); // 生成右侧区域的随机位置,遵循和左侧一致的边界规则 this.x2 = Math.floor(Math.random() * ((this.width / 2) - 50) + (this.width / 2)); this.y = 100; } // 其他方法保持不变 }
公式逻辑拆解
(this.width / 2):右侧区域的起始点,确保元素始终在屏幕中线右侧((this.width / 2) - 50):随机数的取值范围,和左侧的可用空间完全对称,保证左右区域的随机范围一致- 整个公式最终会在
[屏幕中线, 屏幕右边缘-50px]区间生成随机整数,完美避免元素超出右侧边框
完整可运行代码
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); // 地面 } } 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 = Math.floor(Math.random() * ((this.width / 2) - 50) + (this.width / 2)); 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();
CSS和HTML部分保持你原来的代码即可,刷新页面后,两个坦克就会分别在左右两侧的安全区域内随机出现啦!
内容的提问来源于stack exchange,提问作者Zambon
相关产品推荐
相关产品推荐

