简体   繁体   中英

In FabricJS, how can I identify through a set of objects that overlap at the coordinates where the mouse is clicked?

I need to be able to iterate through a set of objects that overlap each other at the coordinates where the mouse if clicked. As a follow-on, I would use bringToFront and then display a nice menu based on that object but I'm unsure of how to even identify and iterate on the set of objects.

My specific need was to iterate over a set of overlapping objects by pressing the tab key to set the active object/group. Below is what I did:

var stackArray = new Array();

canvas.on('mouse:down', function(e){
    var subobj = canvas.getObjects();
    stackArray = [];
    for (var i=0;i<subobj.length;i++) {
        if (subobj[i].id != '' && typeof(subobj[i].id) != 'undefined' && subobj[i].id != 'navpanel' && subobj[i].id != 'header') {

            if (e.target!=null && typeof(e.target.id) != 'undefined') {
                if (subobj[i].intersectsWithObject(canvas.getActiveObject()) && subobj[i].id != e.target.id) {
                    stackArray.push(subobj[i]);
                } else if (subobj[i].id == e.target.id) {
                    stackArray.push(subobj[i]);
                }
            }
        }
    }
});

...

e.preventDefault();
switch(e.keyCode){
    case 9: // tab
        if (stackArray.length > 1) {
            fillObj(canvas.getActiveObject(),'inactive');
            canvas.getActiveObject().sendToBack();

            canvas.setActiveObject(stackArray[stackArray.length-1]);
            fillObj(canvas.getActiveObject(),'active');

            stackArray.splice(0, 0, stackArray.splice(stackArray.length-1,1)[0]);
        }
        break;
}

function fillObj(obj,mode) {
    if (obj.type == 'group') {
        obj = obj.item(0);
    }

    if (mode == 'active') {
        obj.set('fill', 'red');
        obj.set('strokeWidth', 1);
        obj.set('shadow','rgba(0,0,0,0.5) 5px 5px 15px');
    } else if (mode == 'inactive') {
        obj.set('fill', '#333');
        obj.set('strokeWidth', 0);
        obj.set('shadow','');    
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM