Skip to content

Instantly share code, notes, and snippets.

@girliemac
Last active July 22, 2016 21:05
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 girliemac/b3c576ce96129e0e592a to your computer and use it in GitHub Desktop.
Save girliemac/b3c576ce96129e0e592a to your computer and use it in GitHub Desktop.
Snippets for CoDoodler Blog
<canvas id="drawCanvas" width="800" height="600"></canvas>
var canvas = document.getElementById('drawCanvas');
var ctx = canvas.getContext('2d');
ctx.lineWidth = '3';
canvas.addEventListener('mousedown', startDraw, false);
canvas.addEventListener('mousemove', draw, false);
canvas.addEventListener('mouseup', endDraw, false);
// create a flag
var isActive = false;
// array to collect coordinates
var plots = [];
function draw(e) {
if(!isActive) return;
// cross-browser canvas coordinates
var x = e.offsetX || e.layerX - canvas.offsetLeft;
var y = e.offsetY || e.layerY - canvas.offsetTop;
plots.push({x: x, y: y});
drawOnCanvas(plots);
}
function drawOnCanvas(color, plots) {
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 startDraw(e) {
isActive = true;
}
function endDraw(e) {
isActive = false;
// empty the array
plots = [];
}
<script src="https://cdn.pubnub.com/pubnub-3.15.2.min.js"></script>
var channel = 'my-draw-demo';
var pubnub = PUBNUB.init({
publish_key: 'your-publish-key',
subscribe_key: 'your-subscribe-key',
ssl: true
});
pubnub.publish({
channel: channel,
message: {
plots: plots // your array goes here
}
});
pubnub.subscribe({
channel: channel,
callback: drawFromStream
});
function drawFromStream(message) {
if(!message) return;
ctx.beginPath();
drawOnCanvas(message.plots);
}
pubnub.subscribe({
channel: channel,
callback: drawFromStream,
// Add presence
presence: function(m){
document.getElementById('occupancy').textContent = m.occupancy;
}
});
pubnub.history({
channel: 'my-channel',
count: 100,
callback: function(m){ console.log(m) }
});
pubnub.history({
channel: channel,
count: 50,
callback: function(messages) {
pubnub.each( messages[0], drawFromStream );
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment