首页 > 解决方案 > 你如何在fabricjs中进行边界检测?

问题描述

当光标悬停在路径或矩形或其他东西的边缘(仅在边缘而不是对象上)时,我的应用程序需要执行某些操作,但我找不到任何 api 来执行此操作。如何实现?谢谢 。

例如下面的伪代码

path.on('mouse:move', function () {
          if(  mouse on the edge of the path ){
             change the cursor to a star
          }else{
             do nothing
          }
        });

标签: javascriptfabricjs

解决方案


考虑将对象的perPixelTargetFind属性设置为 true。 http://fabricjs.com/docs/fabric.Path.html#perPixelTargetFind

path.perPixelTargetFind = true;

这样你就可以:

canvas.on({
    "mouse:over": (event) => {
        if (event.target == path) {
            change cursor;
        }
        else {
            do nothing;
        }
    }
});

唯一的缺点是当鼠标悬停在对象填充上时它也会触发,因此从技术上讲,如果您只想进行边界检测,您可能必须从对象中删除任何填充。

var pathFill = path.fill;
path.fill = "transparent";

然后,如果您想在鼠标不再悬停在边缘后重置所有内容,您可以:

canvas.on({
    "mouse:out": (event) => {
        if (event.target == path) {
            reset cursor;
            path.fill = pathFill;
        }
        else {
            do nothing;
        }
    }
});

推荐阅读