变换画布不会影响可点击的区域

Transforming a canvas doesnt affect the clickable areas

本文关键字:区域 布不会 影响 变换      更新时间:2023-09-26

我试图通过转换它来改变我的canvas。我用刻度(-1,-1)把它倒过来。但是,画布内的可点击区域不受此转换的影响。对于这个问题,谷歌没有答案。我觉得这很奇怪。有人能解释一下原因吗?并可能给出一个解决这个问题的方法。

这里有一把小提琴。我在研究我的问题时遇到了这个。尝试转换它与CSS规则,如transform:scale(-1,-1);。可点击区域搞砸了,即使代码清楚地从画布上选择像素(被点击)。

如果它只是缩放,那么只需将鼠标转换为相同的。

mouse.x = ?
mouse.y = ?
var scalex = -1;
var scaley = -1;
mouse.tx = mouse.x * scalex;
mouse.ty = mouse.y * scaley;

但是我猜你也移动了你正在画的图像,这样你就可以看到它了。

你可能做了类似

这样的事
var drawImage(image,-200,-200); // move image back onto the canvas

您必须对鼠标做同样的操作(缩放和翻译)。当你做反向变换时你做的是反向变换。所以当你缩放然后平移时,你通过平移然后缩放来反转它。

var box = {  // a hit region in normal screen coordinates.
    x : 20,
    y : 20,
    w : 60,
    h : 60,
}
// the mouse 
mouse.x = ?
mouse.y = ?
// the scale on translations so you can see the box
var scalex = -1;
var scaley = -1;
var originx = -200;
var originy = -200;
// transform the mouse screen coords into transformed canvas space
mouse.tx = mouse.x + orginx;  // translate first
mouse.ty = mouse.y + orginy;
mouse.tx *= scalex;   // then scale
mouse.ty *= scaley;
// draw the transformed image/box/whatever
ctx.scale(scalex,scaley);
ctx.translate(originx,originy);
ctx.strokeRect(box.x,box.y,box.w,box.h);  // draw the back to front box
// is the mouse over the hit region and hence the box
if(mouse.tx > box.x && mouse.tx < box.x + box.w && mouse.ty > box.y && mouse.ty < box.y + box.h){
    ctx.fillStyle = "red"
    ctx.fillRect(box.x,box.y,box.w,box.h);
}

这是一个简单的版本,只有缩放和平移,将适用于所有的缩放和平移,只要你不旋转它。如果你旋转,你需要做完整的反转。你可以在这个问题中找到如何做到这一点HTML画布,鼠标位置后缩放和翻译