-
Notifications
You must be signed in to change notification settings - Fork 0
/
presence.html
98 lines (77 loc) · 1.93 KB
/
presence.html
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
<html>
<body>
<!--
Tutorial:
http://www.pubnub.com/blog/multiuser-draw-html5-canvas-tutorial/
-->
<header>
<h1>CoDoodler: Simplified version</h1>
<h2>Number of doodlers: <span id="occupancy">0</span></h2>
</header>
<canvas id="drawCanvas" width="600" height="480">Canvas not working? :-/</canvas>
<script src="./assets/pubnub.min.js"></script>
<script type="text/javascript">
/* PubNub */
var channel = 'draw';
var pubnub = PUBNUB.init({
publish_key: 'demo',
subscribe_key: 'demo',
});
pubnub.subscribe({
channel: channel,
callback: drawFromStream,
presence: function(m){
if(m.occupancy > 0){
document.getElementById('occupancy').textContent = m.occupancy;
}
}
});
/* Draw on canvas */
var canvas = document.getElementById('drawCanvas');
var ctx = canvas.getContext('2d');
ctx.lineWidth = '3';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
var color = 'yellowgreen';
canvas.addEventListener('mousedown', startDraw, false);
canvas.addEventListener('mousemove', draw, false);
canvas.addEventListener('mouseup', endDraw, false);
function drawOnCanvas(color, plots) {
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(plots[0].x, plots[0].y);
for(var i=1; i<plots.length; i++) {
ctx.lineTo(plots[i].x, plots[i].y);
}
ctx.stroke();
}
function drawFromStream(message) {
if(!message || message.plots.length < 1) return;
drawOnCanvas(message.color, message.plots);
}
var isActive = false;
var plots = [];
function draw(e) {
if(!isActive) return;
var x = e.offsetX || e.layerX - canvas.offsetLeft;
var y = e.offsetY || e.layerY - canvas.offsetTop;
plots.push({x: x, y: y});
drawOnCanvas(color, plots);
}
function startDraw(e) {
isActive = true;
}
function endDraw(e) {
isActive = false;
pubnub.publish({
channel: channel,
message: {
color: color,
plots: plots
}
});
plots = [];
}
</script>
</body>
</html>