javascript - Canvas 对齐问题

标签 javascript html css math canvas

我想生成一个显示 NxN 方 block 的字段。 (在示例中它显示 2x2 红色方 block ) 在 Canvas 的中心。方 block 所在的字段应在 Canvas 中水平和垂直居中。 (当然也是在更改 rowCount 之后)

此外,fieldSize 声明了红色方 block 对齐的计算区域的大小。更改因子将更改字段大小。 (1 == Canvas 大小,0.5 = 1/2 Canvas 大小)


我的问题:

在下面的示例中(很难看清),红色框并没有真正居中,但我希望它们居中。看看这张图片:

Image

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/

相关文章:

javascript - 如何根据在 div 中输入的文本量扩展 div 框(菜单)?

javascript - 管理四位数 ID

javascript - 正则表达式通配符问题

javascript - jQwidgets - 单击 GridView 按钮单元格但不会触发行选择

javascript - 为什么我的 bas64 编码图像创建了一个 http 请求?

html - Wordpress Customizr - 更改正文中的字体大小

javascript - 如果 id 对应则显示元素

javascript - 错误 : No component factory found for GoogleCardLayout2

javascript - 如何访问底层元素上的事件?

jquery - 如何让一个div停留在另一个滚动的div的底部