【发布时间】:2018-10-17 10:09:00
【问题描述】:
我想生成一个显示NxNsquares 的字段。 (在示例中显示 2x2 红色方块) 在画布的中心。方块所在的区域应在画布中水平和垂直居中。 (当然也是在更改 rowCount 之后)
此外,fieldSize 声明了红色方块对齐的计算区域的大小。更改因子将更改字段大小。 (1 == 画布大小,0.5 = 1/2 画布大小)
我的问题:
在下面的示例中(很难看到),红色框并没有真正居中,但我希望它们居中。看看这张图片:
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>
【问题讨论】:
标签: javascript html css math canvas