[英]Distinguish between single select and multiselect event in Fabric.js
I have the following event handling logic in Fabric.js.我在 Fabric.js 中有以下事件处理逻辑。 I am trying to distinguish between the selection of a single object, and the selection of multiple objects (multiselect).我试图区分单个 object 的选择和多个对象的选择(多选)。 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.我已经使用if (obj.updated && obj.deselected.length == 0)
实现了if (obj.isMultiSelect())
) ,但它看起来像一个 hack。 Is there a better way?有没有更好的办法?
Solved with getActiveObjects() method用 getActiveObjects() 方法解决
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.