对于我正在制作的新游戏,我需要在画布底部有 3 个居中且均匀间隔的矩形,但我需要能够添加更多矩形,并让它们均匀间隔(可能没有不过超过5个)
我首先将画布的宽度除以 (NumberOfBoxes),然后将 x 设置为宽度加上一半,但这会导致它们在右墙和最右边的盒子之间有更大的间隙,比左墙和最左边的盒子。
class Box {
constructor(game, x){
this.game = game;
this.width = 150;
this.height = 75;
this.x = this.game.width/this.game.numberOfBoxes*x;
this.y = this.game.height - this.height;
}
draw(context){
context.fillRect(this.x + this.width/2, this.y, this.width, this.height);
}
(被拉入的 x 是告诉每个框要位于画布的哪一部分的变量)
我还尝试使用 mod 来获取框后的剩余空间,然后将部分添加到每个框的 x-pos,但这也不起作用。
这里的技巧是首先计算矩形和画布本身边框之间的空白区域的总宽度。
这是通过将矩形的数量乘以其宽度并从画布的宽度中减去结果来完成的。
((canvas.width - boxesWidth * numberOfBoxes)
要获得实际间隙,我们需要将该数字除以矩形数量 +1 - 这很重要。
let gap = ((canvas.width - boxesWidth * numberOfBoxes) / (numberOfBoxes + 1));
现在只需将屏幕位置增加间隙 + 矩形的宽度并相应地绘制矩形即可。
这是一个例子:
let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");
let boxesWidth = 35;
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height)
let numberOfBoxes = parseInt(document.getElementById("slider").value);
let gap = ((canvas.width - boxesWidth * numberOfBoxes) / (numberOfBoxes + 1));
let x = gap;
for (let a = 0; a < numberOfBoxes; a++) {
context.fillRect(x, 50, boxesWidth, 15);
x += gap + boxesWidth
}
}
document.getElementById("slider").oninput = function() {
draw();
}
draw();
canvas {
background: lightgray;
}
<canvas id="myCanvas"></canvas><br>
<input type="range" min=1 max=7 value=3 id="slider">