FabricJS画布中如何仅选择单个对象而非组对象?
解决Fabric.js多选仅选中单个对象、跳过组的问题
要实现仅选中单个对象、跳过组的多选逻辑,只需要在获取画布对象时过滤掉Group类型的对象即可。Fabric.js中可以通过对象的type属性或者instanceof来判断是否为组。
修改后的多选方法
multiseleccion(){ this.canvas?.discardActiveObject(); // 过滤掉Group类型的对象,仅保留单个对象 const singleObjects = this.canvas?.getObjects().filter(obj => obj.type !== 'group'); this.seleccionar = new fabric.ActiveSelection(singleObjects, { canvas: this.canvas }); this.canvas?.setActiveObject(this.seleccionar); this.canvas?.requestRenderAll(); }
补充说明
也可以用instanceof来判断对象类型,效果一致:
const singleObjects = this.canvas?.getObjects().filter(obj => !(obj instanceof fabric.Group));
你原有的创建代码参考
创建组的代码
const group = new fabric.Group([ new fabric.Rect({ width: 100, height: 100, fill: 'red' }), new fabric.Rect({ width: 100, height: 100, fill: 'yellow', left: 100 }), new fabric.Rect({ width: 100, height: 100, fill: 'blue', top: 100 }), new fabric.Rect({ width: 100, height: 100, fill: 'green', left: 100, top: 100 }) ]) this.canvas.add(group)
创建单个图形的代码
let rect1 = new fabric.Rect( { width: 100, height: 100, fill: 'transparent', stroke: 'blue', left: 140 }); this.canvas.add(rect1)
let rect2 = new fabric.Rect( { width: 100, height: 100, fill: 'transparent', stroke: 'blue', left: 240 }); this.canvas.add(rect2)
内容的提问来源于stack exchange,提问作者jorge jesus achulla palacios
相关产品推荐
相关产品推荐

