简体   繁体   中英

Distinguish between single select and multiselect event in Fabric.js

I have the following event handling logic in Fabric.js. I am trying to distinguish between the selection of a single object, and the selection of multiple objects (multiselect). How can I do this?

Code:

canvas.on({
    'selection:created': handleSelection,
    'selection:updated': handleSelection,
    'selection:cleared': handleSelection,
});

function handleSelection(obj) {
    if (obj.isMultiSelect()) {  // <- ATTENTION. How do I implement this?
        // Do something.
    } else if (obj.isSingleSelect()) {  // <- ATTENTION. How do I implement this?
        // Do another thing.
    }
}

I have implemented if (obj.isMultiSelect()) using if (obj.updated && obj.deselected.length == 0) , but it looks like a hack. Is there a better way?

Solved with getActiveObjects() method

 var canvas = new fabric.Canvas("canvas"); function addCheckbox(left,top, width,height){ var imgClass = new fabric.Image.fromURL('https://image.flaticon.com/icons/svg/33/33281.svg', function(img){ img.width = width; img.height = height; img.left = left; img.top = top; img.on('mousedown', function(e) { if(e.target.opacity <= 0.5){ e.target.opacity = 1; }else{ e.target.opacity = 0.4; } canvas.renderAll(); }); canvas.add(img); canvas.renderAll(); }) } addCheckbox(0,0,100,100) addCheckbox(100,100,100,100) function isMultipleSelected(){ if(canvas.getActiveObjects().length>1){ return true; } return false; } function isSingleSelected(){ if(canvas.getActiveObjects().length== 1){ return true } return false } canvas.on({ 'selection:created': handleSelection, 'selection:updated': handleSelection, 'selection:cleared': handleSelection, }); function handleSelection(obj) { if (isMultipleSelected()) { // <- ATTENTION. How do I implement this? // Do something. console.log("Yes Multiple selected") } else if(isSingleSelected()) { // <- ATTENTION. How do I implement this? // Do another thing. console.log("Yes Single selected") }else { console.log("Nothing selected") } }
 body { background-color:silver; } canvas { border:1px solid red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.3/fabric.min.js"> </script> <button onClick="isMultipleSelected()"> Check Selection </button> <canvas id="canvas" width=300 height=300></canvas><br>

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