我想克隆一些对象。
1- 如何克隆多个活动对象?(我使用的方式:我首先从选定的对象创建一个组。克隆这个组并取消组合回原来的状态。有没有更好的方法我还找不到??)
2-取消组合对象后,它们会丢失之前设置的值(例如 lockMovementY:true )。(如何为多个活动对象设置值??)
3-克隆组没有这个问题。
我正在添加[jsfiddle],以便您可以更好地检查。
谢谢你。
var canvas = new fabric.Canvas('theCanvas', {
width: 500,
height: 200,
});
//Add Rect
let rect = new fabric.Rect({
left: 50,
top: 50,
originX: 'center',
originY: 'center',
fill: '#ffffff',
width: 30,
height: 30,
fill: 'blue',
lockMovementY: true,
centeredScaling: true,
})
canvas.add(rect);
//Rect Ends
//Add Circle
let circle = new fabric.Circle({
top: 50,
left: 90,
originX: 'center',
originY: 'center',
fill: 'red',
opacity: 0.8,
lockMovementY: true,
centeredScaling: true,
radius: 15,
})
canvas.add(circle);
canvas.setActiveObject(circle);
//Circle Ends
//Group
this.group = function() {
if (!canvas.getActiveObject()) {
return;
}
if (canvas.getActiveObject().type !== 'activeSelection') {
return;
}
canvas.getActiveObject().toGroup();
let activeGroup = canvas.getActiveObject();
activeGroup.set({
lockMovementY: true,
centeredScaling: true,
});
canvas.requestRenderAll();
console.info('Group Created from Objects')
}
//Group Ends
//Ungroup
this.ungroup = function() {
if (!canvas.getActiveObject()) {
return;
}
if (canvas.getActiveObject().type !== 'group') {
return;
}
canvas.getActiveObject().toActiveSelection();
canvas.requestRenderAll();
console.info('Group Disbanded')
}
//Ungroup Ends
//Remove Selected Object
function removeSelected() {
var activeObjects = canvas.getActiveObjects();
canvas.discardActiveObject()
if (activeObjects.length) {
canvas.remove.apply(canvas, activeObjects);
}
}
//Remove Object Ends
//Clone-works
this.clone = function() {
if (!canvas.getActiveObject()) {
console.warn('None Active Objects');
return;
}
if (canvas.getActiveObject().type !== 'group') {
this.group();
var object = canvas.getActiveObject();
object.clone(function(clone) {
canvas.add(clone.set({
top:50,
left: 200,
lockMovementY: true,
centeredScaling: true
}));
this.ungroup();
canvas.setActiveObject(clone);
})
this.ungroup();
/*
SET VALUE FOR EACH ACTİVE OBJECT ???
forEachObject.set('lockMovementY','true') ??
*/
}
else{
var object = canvas.getActiveObject();
object.clone(function(clone) {
canvas.add(clone.set({
top:50,
left: 200,
lockMovementY: true,
centeredScaling: true
}));
canvas.setActiveObject(clone);
});
}
}
//Clone Ends
#theCanvas{
border: 1px blue solid;
}
button{
margin: 10px;
padding: 10px 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.2.0/fabric.min.js"></script>
<div>
<button onclick="clone()">Clone</button>
<button onclick="group()">Group</button>
<button onclick="ungroup()">Ungroup</button>
<button onclick="removeSelected()">Delete</button>
</div>
<div class="container">
<div class="fabric-canvas-wrapper" id="fabric-canvas-wrapper">
<canvas id="theCanvas"></canvas>
</div>
</div>