首页 > 解决方案 > 是否可以使用javascripts fillRect() 函数从中心填充

问题描述

我在 js 中使用 fillRect 函数,但似乎输入的坐标似乎位于矩形的左上角,而不是中心,正如我更喜欢的那样。是否有可能的功能或解决方法。

标签: javascripthtml5-canvas

解决方案


此处的文档使用示例

ctx.fillRect(20, 20, 150, 100);

这放置了一个 150x100 的矩形,其左上角为 20,20

但是,如果您希望它以 20,20 为中心,您可以从 x 中减去一半宽度,从 y 中减去一半高度,

ctx.fillRect(20-(150/2), 20-(100/2), 150, 100);

我做了一个小 jsfiddle,中间有一个红点

https://jsfiddle.net/82xzum0f/

如果您需要重复执行,您可以编写自己的函数来为您执行逻辑,

function drawCenterRec(ctx, x, y, width, height) {
      // change x and y by half of the width and half of the height
      // then draw a rectangle on the context.
}

推荐阅读