【发布时间】:2020-01-02 13:28:14
【问题描述】:
我在 2d 画布上绘制简单的形状,同时对形状应用如下变换:
const rect = ({ x, y, width, height }) => {
ctx.fillStyle = 'black';
ctx.fillRect(x, y, width, height);
};
const transform = ({ translate, rotate, scale }, f) => {
// ctx is a 2d canvas context
ctx.save();
if (translate) {
ctx.translate(translate[0], translate[1]);
}
if (rotate) {
ctx.rotate(rotate);
}
if (scale) {
ctx.scale(scale[0], scale[1]);
}
f(ctx);
ctx.restore();
};
const draw = () => {
transform({ translate: [10, 10] }, () => {
rect({ x: 0, y: 0, width: 10, height: 10 });
});
};
现在我需要知道这个矩形在画布空间中的尺寸,以便我可以对鼠标单击位置进行测试。
之前我问过这个问题How to get the 2d dimensions of the object being drawn for hit test on webgl after model view transform 关于 webgl 命中测试检测。但该解决方案不适用于此处,因为我没有转换矩阵。
一种可能的解决方案是,我在称为碰撞画布的不同画布上绘制相同的对象,并使用与对象相关的特定颜色,稍后当我想对画布上的某个位置进行测试时,我查询碰撞画布颜色那个位置,看看颜色是否与对象的特定颜色相匹配,这是个好主意吗?
我认为最好的解决方案是使用ctx.currentTransform 方法。根据物体的尺寸已知,转换后的尺寸可以通过这个函数找到:
function applyTransform(bounds, currentTransform) {
bounds.x = ct.e + bounds.x * ct.a;
bounds.y = ct.f + bounds.y * ct.d;
bounds.width = bounds.width * ct.a;
bounds.height = bounds.height * ct.d;
}
【问题讨论】:
-
您当前的命中检测代码是什么?
-
我还没有,不过我会尝试提到的解决方案
标签: javascript html node.js canvas webgl