javascript - 是否可以使用javascripts fillRect() 函数从中心填充
问题描述
我在 js 中使用 fillRect 函数,但似乎输入的坐标似乎位于矩形的左上角,而不是中心,正如我更喜欢的那样。是否有可能的功能或解决方法。
解决方案
此处的文档使用示例
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.
}
推荐阅读
- python-3.x - Python3.5-如何从函数内部删除(释放GPU内存)变量
- cassandra - Cassandra - 在插入过程中截断表
- postgresql - \set 命令在 EDB Postgresql 中
- azure-devops - 无法从 VS 2019 连接到 Azure DevOps 服务器
- mysql - 为什么 MySQL 拒绝以下查询?
- css - 覆盖电子中的首选颜色方案
- r - 如何使用 R 修复 proxfun.igraph 中的错误
- tensorflow - 生产 - 加载文件以进行快速计算的最佳方法是什么?
- javascript - 使用正则表达式查找数量和项目计数
- java - 如何在 java 中使用密码套件 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 建立 TLS 连接?