问题
I am using
var jsonToPHP= JSON.stringify(canvas.toObject(['id','name']));
to save all from canvas to JSON.
I am also adding background image to canvas.
document.getElementById('imgLoader').addEventListener("change", function (e) { var file = e.target.files[0]; var reader = new FileReader(); reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:canvas.width, height:canvas.height,}).scale(1);
oImg.set('selectable', false);
canvas.add(oImg).renderAll();
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
}); }; reader.readAsDataURL(file);
});
But i would like to exclude background image to be saved to JASON.
I vas googling for:
Exclude element from canvas to be saved to json fabric.js
and i have got next:
in the fabricjs docs there is a property for the Object class calles 'excludeFromExport'.
Once set to true it should do exactly what you want.
www.fabricjs.com/docs
I went to:
Source: fabric.js, line 12350 excludeFromExport
And what now?
My knowlage is to less to get to result from this. Does any one can give more informations: maybe one example?
Thank you
回答1:
DEMO
document.getElementById('imgLoader').addEventListener("change", function(e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function(f) {
var data = f.target.result;
fabric.Image.fromURL(data, function(img) {
var oImg = img.set({
left: 0,
top: 0,
angle: 00,
width: canvas.width,
height: canvas.height
});
canvas.setBackgroundImage(oImg).renderAll();
var dataURL = canvas.toDataURL({
format: 'png',
quality: 0.8
});
});
};
reader.readAsDataURL(file);
});
var canvas = new fabric.Canvas('c', {
serializeBgOverlay: false //to serialize background data toJson
});
canvas.backgroundColor = 'green';
canvas.add(new fabric.Circle({
left: 50,
top: 50,
radius: 50,
stroke: 'red',
fill: ''
}))
canvas.renderAll();
// override _toObjectMethod and if you want to serialize background , set serializeBgOverlay true, while canvas initialize
fabric.StaticCanvas.prototype._toObjectMethod = function(methodName, propertiesToInclude) {
var data = {
objects: this._toObjects(methodName, propertiesToInclude)
};
if (this.serializeBgOverlay) {
fabric.util.object.extend(data, this.__serializeBgOverlay(methodName, propertiesToInclude));
}
fabric.util.populateWithProperties(this, data, propertiesToInclude);
return data;
}
function exportToJson() {
console.log(canvas.toJSON());
}
canvas{
border:2px dotted blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.16/fabric.min.js"></script>
<input type="file" id="imgLoader" accept="image/*"> <br>
<canvas id='c' width='400' height='400'></canvas>
<button onclick='exportToJson();'>ToJson</button>
Here I added a prototype of _toObjectMethod() , it will exclude background image of canvas toJson export.
来源:https://stackoverflow.com/questions/45158186/exclude-element-from-canvas-to-be-saved-to-json-fabric-js