-
Install Node.js from nodejs.org
-
Create and navigate into application directory
-
Create package.json
// Example package.json
{
"name": "Socket.IO Drawing Tutorial",
"version": "1.0.0",
"author": "Peter Stakoun"
}
- Install Express
$ npm install express --save
- Install Socket.IO
$ npm install socket.io --save
- Create public/index.html
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Drawing Tutorial</title>
<link rel="stylesheet" href="style.css" />
<script src="/socket.io/socket.io.js"></script>
<script src="script.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
- Create public/style.css
html, body {
margin: 0;
width: 100%;
height: 100%;
}
#canvas {
display: block;
}
-
Create app.js
-
Add imports
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
- Specify client file path
app.use(express.static(__dirname + '/public'));
- Create server
var port = 3000;
http.listen(port, function() {
console.log('Server running on port ' + port);
});
- Run the server
$ node app
-
See your app (currently a blank page) at localhost:3000
-
Add event handling
io.on('connection', function (socket) {
socket.on('draw', function (data) {
socket.broadcast.emit('draw', data);
});
});
-
Create public/script.js
-
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;
}
- Handle mouse up event
canvas.onmouseup = function(e) {
drawing = false;
}
- Handle mouse move event
canvas.onmousemove = function(e) {
- Update mouse coordinates
x = e.clientX;
y = e.clientY;
- Check if mouse down
if (drawing) {
- Send mouse location to server
socket.emit('draw', {
'x1': prevX,
'y1': prevY,
'x2': x,
'y2': y
});
- Draw on client
drawLine(context, prevX, prevY, x, y);
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);
});
});
- Run the server
$ node app
- See your completed app at localhost:3000