我想生成一个显示 NxN
方 block 的字段。 (在示例中它显示 2x2 红色方 block ) 在 Canvas 的中心。方 block 所在的字段应在 Canvas 中水平和垂直居中。 (当然也是在更改 rowCount 之后)
此外,fieldSize 声明了红色方 block 对齐的计算区域的大小。更改因子将更改字段大小。 (1 == Canvas 大小,0.5 = 1/2 Canvas 大小)
我的问题:
在下面的示例中(很难看清),红色框并没有真正居中,但我希望它们居中。看看这张图片:
let canvas = document.getElementById("canvas")
/* edit these values */
let rowCount = 2
let fieldSize = canvas.width * 0.8
/********************/
let ctx = canvas.getContext("2d")
for (let y = 0; y < rowCount; y++) {
for (let x = 0; x < rowCount; x++) {
let squareSize = (fieldSize / rowCount) * 0.7
let positionX = (fieldSize / rowCount) * (x) + (canvas.width - fieldSize) * 0.5
let positionY = (fieldSize / rowCount) * (y) + (canvas.width - fieldSize) * 0.5
ctx.rect(positionX, positionY, squareSize, squareSize);
ctx.fillStyle = "red"
ctx.fill()
}
}
<canvas style="background: green" id="canvas" width="300" height="300" id="codeCanvas"></canvas>
最佳答案
你可以这样做(它适用于任意数量的行):
(canvas.width - fieldSize) / 2)
用于字段的填充
x * (fieldSize / rowCount)
为每个方 block 的相对位置
(fieldSize / rowCount - squareSize) / 2
用于每个正方形的填充,而您的代码中缺少它
/* edit these values */
let rowCount = 2
let fieldSize = canvas.width * 0.8
let squareSize = (fieldSize / rowCount) * 0.8
/********************/
let ctx = canvas.getContext("2d")
for (let y = 0; y < rowCount; y++) {
for (let x = 0; x < rowCount; x++) {
let positionX = (canvas.width - fieldSize) / 2 + x * (fieldSize / rowCount) + (fieldSize / rowCount - squareSize) / 2
let positionY = (canvas.width - fieldSize) / 2 + y * (fieldSize / rowCount) + (fieldSize / rowCount - squareSize) / 2
ctx.rect(positionX, positionY, squareSize, squareSize);
ctx.fillStyle = "red"
ctx.fill()
}
}
<canvas style="background: green" id="canvas" width="300" height="300" id="codeCanvas"></canvas>
关于javascript - Canvas 对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50216967/