我正在尝试克隆一个画布对象,然后将克隆的画布上的覆盖图像替换为另一个。到目前为止,这是我尝试过的:
_canvas.clone(function(cloneCanvas) {
cloneCanvas.scale = _canvas.scale;
cloneCanvas = self.pdcZoom.resetZoomBeforeSave(cloneCanvas);
var src = config.media_url + _sidesConfig[tester]["filename"];
cloneCanvas.overlayImage = null;
fabric.Image.fromURL(src, function(img) {
img.set({
width: parseFloat(_canvas.width),
height: parseFloat(_canvas.height),
originX: 'left',
originY: 'top',
top: 0,
left: 0,
alignX: options.alignX || 'none', // none, mid, min, max
alignY: options.alignY || 'none',
meetOrSlice: options.meetOrSlice || 'meet', // meet,
isrc: src,
object_type: 'mask',
price: options.price || 0
});
cloneCanvas.setOverlayImage(img, cloneCanvas.renderAll.bind(cloneCanvas));
//self.hideLoadingBar();
});
});
_canvas
是原始画布,cloneCanvas
是新画布。
答案 0 :(得分:0)
要克隆画布,请使用canvas.toJSON(),然后使用loadFromJSON加载json。
var canvas = new fabric.Canvas("c");
var canvas1 = new fabric.Canvas("c1");
canvas.add(new fabric.Circle({
radius: 50
}));
setOverlay('https://picsum.photos/200/300/?random', canvas);
function setOverlay(url, can) {
fabric.Image.fromURL(url, function(img) {
img.set({
scaleX: can.width / img.width,
scaleY: can.height / img.height,
excludeFromExport: true,
opacity:0.5
})
can.setOverlayImage(img);
can.renderAll();
})
}
function clone() {
var json = canvas.toJSON();
canvas1.loadFromJSON(json, function() {
setOverlay('https://picsum.photos/200/400/?random', canvas1);
})
}
canvas{
border:2px solid;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id='c' width=300 height=300></canvas><br>
<button onclick='clone()'>clone</button>
<canvas id='c1' width=400 height=400></canvas>