-
Notifications
You must be signed in to change notification settings - Fork 22
/
opentok-whiteboard.js
432 lines (381 loc) · 17.1 KB
/
opentok-whiteboard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*!
* opentok-whiteboard (http://github.com/aullman/opentok-whiteboard)
*
* Shared Whiteboard that works with OpenTok
*
* @Author: Adam Ullman (http://github.com/aullman)
* @Copyright (c) 2014 Adam Ullman
* @License: Released under the MIT license (http://opensource.org/licenses/MIT)
**/
var ng, p;
if (typeof angular === 'undefined' && typeof require !== 'undefined') {
ng = require('angular');
} else {
ng = angular;
}
if (typeof paper === 'undefined' && typeof require !== 'undefined') {
p = require('paper');
} else {
p = paper;
}
var OpenTokWhiteboard = ng.module('opentok-whiteboard', ['opentok'])
.directive('otWhiteboard', ['OTSession', '$window', function (OTSession, $window) {
return {
restrict: 'E',
template: '<canvas hidpi="off"></canvas>' +
'<div class="OT_panel">' +
'<input type="button" ng-class="{OT_color: true, OT_selected: c[\'background-color\'] === color}" ' +
'ng-repeat="c in colors" ng-style="c" ng-click="changeColor(c)">' +
'</input>' +
'<input type="button" ng-click="erase()" ng-class="{OT_erase: true, OT_selected: erasing}"' +
' value="Eraser"></input>' +
'<a class="OT_capture" download="whiteboard_capture.png" ng-click="capture()">{{captureText}}</a>' +
'<input type="button" ng-click="undo()" class="OT_capture" value="Undo"></input>' +
'<input type="button" ng-click="redo()" class="OT_capture" value="Redo"></input>' +
'<input type="button" ng-click="clear()" class="OT_clear" value="Clear"></input>',
link: function (scope, element, attrs) {
var canvas = element.context.querySelector("canvas"),
captureButton = element.context.querySelector('.OT_capture'),
client = {dragging:false},
count = 0, //Grabs the total count of each continuous stroke
undoStack = [], //Stores the value of start and count for each continuous stroke
redoStack = [], //When undo pops, data is sent to redoStack
pathStack = [],
drawHistory = [],
drawHistoryReceivedFrom,
drawHistoryReceived,
batchUpdates = [],
resizeTimeout,
iOS = /(iPad|iPhone|iPod)/g.test( navigator.userAgent );
// Create an empty project and a view for the canvas
p.setup(canvas);
// Set canvas size
canvas.width = attrs.width || element.width();
canvas.height = attrs.height || element.height();
// Set paper.js view size
p.view.viewSize = new p.Size(canvas.width, canvas.height);
p.view.draw();
scope.colors = [{'background-color': 'black'},
{'background-color': 'blue'},
{'background-color': 'red'},
{'background-color': 'green'},
{'background-color': 'orange'},
{'background-color': 'purple'},
{'background-color': 'brown'}];
scope.captureText = iOS ? 'Email' : 'Capture';
scope.strokeCap = 'round';
scope.strokeJoin = 'round';
scope.lineWidth = 2;
var clearCanvas = function () {
p.project.clear();
p.view.update();
drawHistory = [];
pathStack = [];
undoStack = [];
redoStack = [];
count = 0;
};
scope.changeColor = function (color) {
scope.color = color['background-color'];
scope.erasing = false;
};
scope.changeColor(scope.colors[Math.floor(Math.random() * scope.colors.length)]);
scope.clear = function () {
clearCanvas();
if (OTSession.session) {
OTSession.session.signal({
type: 'otWhiteboard_clear'
});
}
};
scope.erase = function () {
scope.erasing = true;
};
scope.capture = function () {
if (iOS) {
// On iOS you can put HTML in a mailto: link
$window.location.href = "mailto:?subject=Whiteboard&Body=<img src='" + canvas.toDataURL('image/png') + "'>";
} else {
// We just download the canvas
captureButton.href = canvas.toDataURL('image/png');
}
};
scope.undo = function () {
if (!undoStack.length)
return;
var uuid = undoStack.pop();
undoWhiteBoard(uuid);
sendUpdate('otWhiteboard_undo', uuid);
};
var undoWhiteBoard = function (uuid) {
redoStack.push(uuid);
pathStack.forEach(function(path) {
if (path.uuid === uuid) {
path.visible = false;
p.view.update();
}
});
drawHistory.forEach(function(update) {
if (update.uuid === uuid) {
update.visible = false;
}
});
};
scope.redo = function () {
if (!redoStack.length)
return;
var uuid = redoStack.pop();
redoWhiteBoard(uuid);
sendUpdate('otWhiteboard_redo', uuid);
};
var redoWhiteBoard = function (uuid) {
undoStack.push(uuid);
pathStack.forEach(function(path) {
if (path.uuid === uuid) {
path.visible = true;
p.view.update();
}
});
drawHistory.forEach(function(update) {
if (update.uuid === uuid) {
update.visible = true;
}
});
};
var draw = function (update) {
drawHistory.push(update);
switch (update.event) {
case 'start':
var path = new p.Path();
path.selected = false;
path.strokeColor = update.color;
path.strokeWidth = scope.lineWidth;
path.strokeCap = scope.strokeCap;
path.strokeJoin = scope.strokeJoin;
path.uuid = update.uuid;
if (update.mode === 'eraser') {
path.blendMode = 'destination-out';
path.strokeWidth = 50;
}
if (ng.isDefined(update.visible)) {
path.visible = update.visible;
}
var start = new p.Point(update.fromX, update.fromY);
path.moveTo(start);
p.view.draw();
pathStack.push(path);
break;
case 'drag':
pathStack.forEach(function(path) {
if (path.uuid === update.uuid) {
path.add(update.toX, update.toY);
p.view.draw();
}
});
break;
case 'end':
pathStack.forEach(function(path) {
if (path.uuid === update.uuid) {
undoStack.push(path.uuid);
path.simplify();
p.view.draw();
}
});
break;
}
};
var drawUpdates = function (updates) {
updates.forEach(function (update) {
draw(update);
});
};
var batchSignal = function (type, data, toConnection) {
// We send data in small chunks so that they fit in a signal
// Each packet is maximum ~250 chars, we can fit 8192/250 ~= 32 updates per signal
var dataCopy = data.slice();
var signalError = function (err) {
if (err) {
TB.error(err);
}
};
while(dataCopy.length) {
var dataChunk = dataCopy.splice(0, Math.min(dataCopy.length, 32));
var signal = {
type: type,
data: JSON.stringify(dataChunk)
};
if (toConnection) signal.to = toConnection;
OTSession.session.signal(signal, signalError);
}
};
var updateTimeout;
var sendUpdate = function (type, update, toConnection) {
if (OTSession.session) {
batchUpdates.push(update);
if (!updateTimeout) {
updateTimeout = setTimeout(function () {
batchSignal(type, batchUpdates, toConnection);
batchUpdates = [];
updateTimeout = null;
}, 100);
}
}
};
var requestHistory = function() {
OTSession.session.signal({
type: 'otWhiteboard_request_history'
});
};
ng.element(document).on('keyup', function (event) {
if (event.ctrlKey) {
if (event.keyCode === 90)
scope.undo();
if (event.keyCode === 89)
scope.redo();
}
});
/*
* The Nuts
* During the process of drawing, we collect coordinates on every [mouse|touch]move event.
* These events occur as fast as the browser can create them, and is computer/browser dependent
*
*/
ng.element(canvas).on('mousedown mousemove mouseup mouseout touchstart touchmove touchend touchcancel',
function (event) {
if ((event.type === 'mousemove' || event.type === 'touchmove' || event.type === 'mouseout') && !client.dragging) {
// Ignore mouse move Events if we're not dragging
return;
}
event.preventDefault();
var offset = ng.element(canvas).offset(),
scaleX = canvas.width / element.width(),
scaleY = canvas.height / element.height(),
offsetX = event.offsetX || event.originalEvent.pageX - offset.left ||
event.originalEvent.touches[0].pageX - offset.left,
offsetY = event.offsetY || event.originalEvent.pageY - offset.top ||
event.originalEvent.touches[0].pageY - offset.top,
x = offsetX * scaleX,
y = offsetY * scaleY,
mode = scope.erasing ? 'eraser' : 'pen',
update;
switch (event.type) {
case 'mousedown':
case 'touchstart':
// Start dragging
client.dragging = true;
client.lastX = x;
client.lastY = y;
client.uuid = parseInt(x) + parseInt(y) + Math.random().toString(36).substring(2);
update = {
id: OTSession.session && OTSession.session.connection &&
OTSession.session.connection.connectionId,
uuid: client.uuid,
fromX: client.lastX,
fromY: client.lastY,
mode: mode,
color: scope.color,
event: 'start'
};
draw(update);
sendUpdate('otWhiteboard_update', update);
break;
case 'mousemove':
case 'touchmove':
offsetX = event.offsetX || event.originalEvent.pageX - offset.left ||
event.originalEvent.touches[0].pageX - offset.left,
offsetY = event.offsetY || event.originalEvent.pageY - offset.top ||
event.originalEvent.touches[0].pageY - offset.top,
x = offsetX * scaleX,
y = offsetY * scaleY;
if (client.dragging) {
// Build update object
update = {
id: OTSession.session && OTSession.session.connection &&
OTSession.session.connection.connectionId,
uuid: client.uuid,
fromX: client.lastX,
fromY: client.lastY,
toX: x,
toY: y,
event: 'drag'
};
count++;
redoStack = [];
client.lastX = x;
client.lastY = y;
draw(update);
sendUpdate('otWhiteboard_update', update);
}
break;
case 'touchcancel':
case 'mouseup':
case 'touchend':
case 'mouseout':
if (count) {
update = {
id: OTSession.session && OTSession.session.connection &&
OTSession.session.connection.connectionId,
uuid: client.uuid,
event: 'end'
};
draw(update);
sendUpdate('otWhiteboard_update', update);
}
client.dragging = false;
client.uuid = false;
}
});
if (OTSession.session) {
if (OTSession.session.isConnected()) {
requestHistory();
}
OTSession.session.on({
sessionConnected: function() {
requestHistory();
},
'signal:otWhiteboard_update': function (event) {
if (event.from.connectionId !== OTSession.session.connection.connectionId) {
drawUpdates(JSON.parse(event.data));
scope.$emit('otWhiteboardUpdate');
}
},
'signal:otWhiteboard_undo': function (event) {
if (event.from.connectionId !== OTSession.session.connection.connectionId) {
JSON.parse(event.data).forEach(function (data) {
undoWhiteBoard(data);
});
scope.$emit('otWhiteboardUpdate');
}
},
'signal:otWhiteboard_redo': function (event) {
if (event.from.connectionId !== OTSession.session.connection.connectionId) {
JSON.parse(event.data).forEach(function (data) {
redoWhiteBoard(data);
});
scope.$emit('otWhiteboardUpdate');
}
},
'signal:otWhiteboard_history': function (event) {
// We will receive these from everyone in the room, only listen to the first
// person. Also the data is chunked together so we need all of that person's
if (!drawHistoryReceivedFrom || drawHistoryReceivedFrom === event.from.connectionId) {
drawHistoryReceivedFrom = event.from.connectionId;
drawUpdates(JSON.parse(event.data));
scope.$emit('otWhiteboardUpdate');
}
},
'signal:otWhiteboard_clear': function (event) {
if (event.from.connectionId !== OTSession.session.connection.connectionId) {
clearCanvas();
}
},
'signal:otWhiteboard_request_history': function (event) {
if (drawHistory.length > 0) {
batchSignal('otWhiteboard_history', drawHistory, event.from);
}
}
});
}
}
};
}]);