Reputation: 41
There are two canvas instance, the smaller 'd' for free drawing, the bigger 'c' is to be added on. How can I only add the boundary of drawing on 'd' to 'c', not the entire 'd' canvas area with lots of empty area to 'c'?
I hope the code can explains more clear. thanks.
HTML
<canvas width="300" height="300" id="c"></canvas>
<canvas width="150" height="150" id="d"></canvas>
<button id="btn">add To c</button>
JavaScript
var c = new fabric.Canvas('c')
var d = new fabric.Canvas('d', {
isDrawingMode: true
})
document.getElementById('btn').onclick = addDrawToBig
function addDrawToBig(){
var svg = d.toSVG()
fabric.loadSVGFromString(svg,function(objects, options) {
var obj = fabric.util.groupSVGElements(objects, options);
c.add(obj).centerObject(obj).setActiveObject(obj);
});
}
var circle = new fabric.Circle({
stroke: 'red',
radius: 15,
left: 15,
top: 15
})
d.add(circle)
d.renderAll()
addDrawToBig()
Upvotes: 3
Views: 1475
Reputation: 41
finally i find the answer to my question, just use fabric.Group and .clone() method:
function addDrawToBig(){
var group = [ ]
d.getObjects().forEach(function(path){
path.clone(function(copy){
group.push(copy);
});
});
group = new fabric.Group( group )
c.add(group).centerObject(group).setActiveObject(group);
}
Special thanks to @AndreaBogazzi, wish a good day!
Upvotes: 1
Reputation: 14741
i updated your fiddle with something that works better. Fiddle
Canvas.toSVG() is not meant to be used as a export import function.
I suggest you to cycle throught the canvas objects and clone all of them in the new canvas. This demo is not really cloning them, just copying them on the other canvas. Without cloning you have the side effect that if you modify something in one canvas the modification get mirrored in the other. You should add
c.add(ao[i].clone());
But for some reason free drawing path .clone() is failing. ( will look in this next days to see if it is a bug or a misusage )
var c = new fabric.Canvas('c')
var d = new fabric.Canvas('d', {
isDrawingMode: true
})
document.getElementById('btn').onclick = addDrawToBig
function addDrawToBig(){
var ao = d.getObjects();
console.log(ao);
for(var i in ao) {
c.add(ao[i]);
}
}
var circle = new fabric.Circle({
stroke: 'red',
radius: 15,
left: 15,
top: 15
})
d.add(circle)
d.renderAll()
addDrawToBig()
Hope it helps.
Upvotes: 0