-
Create and navigate into application directory
-
Install Express
$ npm install express --save
- Install Socket.IO
$ npm install socket.io --save
- Event handling
io.on('connection', function (socket) {
socket.on('draw', function (data) {
socket.broadcast.emit('draw', data);
});
});
- Define function to draw lines on client
function drawLine(context, x1, y1, x2, y2) {
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
}
- Excecute script when content loaded
document.addEventListener("DOMContentLoaded", function() {
- Set up canvas
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var width = window.innerWidth;
var height = window.innerHeight;
canvas.width = width;
canvas.height = height;
- Add mouse state variables
var drawing = false;
var x, y, prevX, prevY;
- Connect to server
var socket = io.connect();
- Handle mouse down event
canvas.onmousedown = function(e) {
drawing = true;
prevX = x;
prevY = y;
}
- Add listener for drawing from other clients
socket.on('draw', function(data) {
drawLine(context, data.x1, data.y1, data.x2, data.y2);
});
});