I want to club multiple canvas images into a mega canvas which has all these individual images from different fabric canvases arranged at different positions. In other words, I want to stitch multiple canvases into one mega canvas. Is there a method where I can specify image data to be transferred from source canvas to destination canvas, also specifying where in destination canvas I want this transferred?
Serialise all the object from canvases using toJSON()
. Then you can use fabric.util.enlivenObjects to load in your mega canvas.
DEMO
var canvas1 = new fabric.Canvas('c1');
var canvas2 = new fabric.Canvas('c2');
var canvas3 = new fabric.Canvas('c3');
canvas1.add(new fabric.Rect({
left: 10,
top: 10,
width: 50,
height: 50,
fill: '#4169e1'
}));
canvas2.add(new fabric.Rect({
left: 30,
top: 40,
width: 50,
height: 50,
fill: '#113232'
}));
function mergeToCanvas(){
var json1 = [],json2 = [];
canvas1.getObjects().map(function(x){
json1.push(x.toJSON());
});
canvas2.getObjects().map(function(x){
json2.push(x.toJSON());
});
canvas3.clear();
fabric.util.enlivenObjects(json1, function(objects) {
canvas3.add(...objects);
});
fabric.util.enlivenObjects(json2, function(objects) {
canvas3.add(...objects);
});
}
canvas {
border: 1px solid black;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c1" width="200" height="100"></canvas>
<canvas id="c2" width="200" height="100"></canvas>
<br>
<button onclick='mergeToCanvas()'>mergeToCanvas</button> <br>
<canvas id="c3" width="200" height="200"></canvas>