Add free drawing result to another canvas in fabricjs

There are two instances of canvas, one smaller "d" for free drawing, more "c" added. How can I only add a drawing border on 'd' to 'c' and not on the whole canvas area d with a lot of empty area before 'c'?

Fiddle

Hopefully the code can explain more clearly. thank.

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()

      

+3


source to share


2 answers


Finally I will 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);
}

      



violin here

Special thanks to @AndreaBogazzi, have a nice day!

0


source


i have updated your fiddle with something that works better. Fiddle

Canvas.toSVG () is not intended to be used as an export import function.

I suggest you cycle through the canvas objects and clone them all in the new canvas. This demo doesn't actually clone them, just copy them to another canvas. Without cloning, you have a side effect: if you modify something in one canvas, then the modification will be mirrored in the other. You must add

c.add(ao[i].clone());

      



But somehow the free drawing path .clone () doesn't work. (look in the following days to see if this is a bug or misuse)

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.

0


source







All Articles