Skip to content

Instantly share code, notes, and snippets.

@Pawan-Bishnoi
Created November 10, 2017 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pawan-Bishnoi/4cb9bc8aa8df804d8a75aee17a356da6 to your computer and use it in GitHub Desktop.
Save Pawan-Bishnoi/4cb9bc8aa8df804d8a75aee17a356da6 to your computer and use it in GitHub Desktop.
FabricJS := Send real time data of free hand drawing to remote users
/*
* We keep two canvases to mimic remote user behaviour
* Events from canvas_left should also reach canvas_right
*/
var canvas_left = new fabric.Canvas ('canvas1');
var canvas_right = new fabric.Canvas ('canvas2');
// is_down := keeps track if the mouse is down
// to distinguish mousemove and mousedrag
var is_down = false;
var count = 1; // we use this to send different id each time. To make it feel like it is coming from different users.
canvas_left.isDrawingMode = true;
canvas_right.isDrawingMode = true;
/*
* Publisher End:
* Event listeners for canvas_left
* These events need to be sent to the other canvas
* in real application this data transfer would most likely happen via websockets */
canvas_left.on ('mouse:down', function (ev) {
is_down = true;
handle_mouse_down (++count, this.getPointer(ev.e));
return true;
});
canvas_left.on ('mouse:move', function (ev) {
if (!is_down)
return true;
handle_mouse_drag (count, this.getPointer(ev.e));
return true;
});
canvas_left.on ('mouse:up', function (ev) {
is_down = false;
handle_mouse_up (count, this.getPointer(ev.e));
return true;
});
/*
* Receiver end:
* Here we receive events and act on them */
var remote_brush = {};
function handle_mouse_down (id, point) {
var brush;
// The id should be user_id so that we keep a brush instance
// for every active user.
// This gives us flexibility to create n number of paths in parallel.
if (!remote_brush[id]) {
remote_brush [id] = new fabric.PencilBrush(canvas_right);
}
brush = remote_brush [id];
brush.onMouseDown (point);
}
function handle_mouse_drag (id, point) {
var brush = remote_brush [id];
if (brush)
brush.onMouseMove (point);
}
function handle_mouse_up (id, point) {
var brush = remote_brush [id];
brush.onMouseUp (point);
delete remote_brush [id];
}
<html>
<head>
<script src="./fabric.js">
</script>
</head>
<body>
<canvas id="canvas1" width="400" height="450" style="border:1px solid #000000; display: inline-block;"> </canvas>
<canvas id="canvas2" width="300" height="450" style="border:1px solid #000000; display: inline-block;"> </canvas>
<script src="./core.js">
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment