Custom Image Object in fabric.js
Custom Image Object
by Vijay Gujar
HTML
<script src="https://raw.github.com/kangax/fabric.js/master/dist/all.js"></script>
<button id="btnAddImage">1 - Add Image</button>
<button id="btnAddCustomImage">2 - Add Custom Image</button>
<button id="btnSerializeToJSON">3 - Serialize to JSON</button>
<button id="btnConsoleLogJSON">4 - console.log(json)</button>
<button id="btnClearCanvas">5 - Clear Canvas</button>
<button id="btnRestore">6 - Restore</button>
<canvas id="canvas" width="400" height="400"></canvas>
CSS
canvas{
border-width: 1px;
border-style: solid;
border-color: #333;
}
JavaScript
var src = 'https://www.google.com/images/srpr/logo3w.png';
var src2 = 'http://www.google.com/logos/2012/Santos_Dumont-2012-hp.jpg';
var json;
var canvas = new fabric.Canvas("canvas");
///////////////////////////////////////////////////////////////
// create Custom Image class from Image class
fabric.CustomImage = fabric.util.createClass(fabric.Image, {
type: 'custom-image',
initialize: function(element, options) {
this.callSuper('initialize', element, options);
options && this.set('name', options.name);
},
toObject: function() {
return fabric.util.object.extend(this.callSuper('toObject'),
{name: this.name});
}
});
fabric.CustomImage.fromObject = function(object, callback) {
fabric.util.loadImage(object.src, function(img) {
callback && callback(new fabric.CustomImage(img, object));
});
};
fabric.CustomImage.async = true;
///////////////////////////////////////////////////////////////
$("#btnAddImage").click(function(){
fabric.util.loadImage(src, function(img) {
var object = new fabric.Image(img);
object.set({
left: 150,
top: 80
});
canvas.add(object);
canvas.renderAll();
});
});
$("#btnAddCustomImage").click(function(){
fabric.util.loadImage(src2, function(img) {
var customImage = new fabric.CustomImage(img, {name: 'foobar'});
customImage.top = 200;
customImage.left = 210;
canvas.add(customImage);
canvas.renderAll();
});
});
$("#btnSerializeToJSON").click(function(){
json = JSON.stringify(canvas)
});
$("#btnConsoleLogJSON").click(function(){
console.log(json);
});
$("#btnClearCanvas").click(function(){
canvas.clear();
});
$("#btnRestore").click(function(){
canvas.loadFromJSON(json, function(){
canvas.renderAll();
});
});