Cesar Jr Rodriguez Cesar Jr Rodriguez - 2 months ago 28
Javascript Question

How to detect when the content of a canvas was changed?

I need to watch the changes in an canvas object (I'm using fabricjs library).

var canvas = this.__canvas = new fabric.Canvas('canvas', {isDrawingMode:true});
//I need to watch the changes here ->
canvas.toJSON();


I try out with Object.prototype.watch() like:


canvas.toJSON.watch('objects', function(){
//dosomething});


But that hasn't worked for me, any help?

Answer

Since your example mentioned isDrawingMode:true I think you are looking for a way to detect the drawing on you canvas in free hand mode.

Fabric JS expose a long list of events, as you can read here.

So if you want to detect the free drawing on your canvas you can use path:created event.

var canvas = new fabric.Canvas('canvas',{isDrawingMode:true});
canvas.on('path:created', function(event) {
    //log the svg path  info
   console.log(event.path.path);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<canvas id="canvas" width="300" height="300"></canvas>