Paper.js:hitTest通过鼠标事件检测被阻挡的项目

Paper.js: hitTest for obstructed items with mouse event?

本文关键字:检测 项目 事件 鼠标 js hitTest Paper      更新时间:2023-09-26

我有两个项目,一个在另一个上,也就是说,一个阻塞另一个。假设Item2被Item1阻止。现在每当我使用

project.hitTest(Item2);

它运行良好。

但当我使用鼠标的event.point时,问题就出现了

project.hitTest(event.point);

在中

function onMouseUp(event){} 

它只检测顶部的项目。是否可以检测所有项目?

也许这会对您有所帮助:
http://paperjs.org/reference/item/#contains-点

var path = new Path.Star({
center: [50, 50],
points: 12,
radius1: 20,
radius2: 40,
fillColor: 'black'
});
// Whenever the user presses the mouse:
function onMouseDown(event) {
// If the position of the mouse is within the path,
// set its fill color to red, otherwise set it to
// black:
if (path.contains(event.point)) {
    path.fillColor = 'red';
} else {
    path.fillColor = 'black';
}
}

这不是最好的解决方案,因为你必须循环所有的路径,但我现在不知道更好的解决方案。

对于较新的paper.js版本,获取所有项目的一种直接方法是使用hitTestAll():

在指定点的位置对项目及其子项(如果是组或层)执行命中测试,返回所有找到的命中。

示例:

var hitOptions = {
    segments: true,
    stroke: true,
    fill: true,
    tolerance: 5,
};

function onMouseUp(event) {
    console.log('******************************************');
    var hitResult = project.hitTestAll(event.point, hitOptions);
    console.log('hitResult (' + hitResult.length + ')' , hitResult);
    if (hitResult) {
        // do something...
    }
}

或者,您可以尝试使用带有options.match过滤器功能的普通hitTest()。示例2-只有在最底部的对象被击中时才返回命中结果:

function hitMatchFilter(hitResult) {
    //console.log('hitMatchFilter:', hitResult);
    let flag_obj_is_first = false;
    if (hitResult.item) {
        let hititem = hitResult.item;
        if (hititem.parent.children[0] == hititem) {
            //console.log('hititem isFirst in parent child list');
            flag_obj_is_first = true;
        }
    }
    return flag_obj_is_first;
}
var hitOptions = {
    segments: true,
    stroke: true,
    fill: true,
    tolerance: 5,
    match: hitMatchFilter,
};
function onMouseUp(event) {
    console.log('******************************************');
    var hitResult = project.hitTest(event.point, hitOptions);
    console.log('hitResult', hitResult);
    if (hitResult) {
        // do something...
    }
}

参考:http://paperjs.org/examples/hit-testing/

击球手必须有像这样的命中选项

var hitOptions={分段:true,笔划:true,fill:true,公差:5};

var hitResult=项目.hitTest(event.point,hitOptions);