1 server.js服务器端,自行下载所需模块
var http = require('http');
var fs = require("fs");
var server = http.createServer(function(req,res){
if(req.url=="/"){
fs.readFile('./index.html',function(err,data){
res.end(data);
})
}
})
var io = require("socket.io")(server);
io.on("connection",function(socket){
socket.on("play",function(msg){
io.emit('answer',msg); //这里使用io为广播
})
})
server.listen(3000,"127.0.0.1");
2.index.html 客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<canvas width="1000" height="600" id="canvas" style="border:1px solid #000;"></canvas>
</body>
</html>
<script src="/socket.io/socket.io.js"></script>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.onmousedown = function(){
canvas.addEventListener("mousemove",handler);
}
canvas.onmouseup = function(){
canvas.removeEventListener("mousemove",handler);
}
function handler(e){
ctx.beginPath();
ctx.arc(e.pageX,e.pageY,20,0,Math.PI*2,true);
ctx.fill();
socket.emit('play',{"x":e.pageX,"y":e.pageY});
}
var socket = io();
socket.on('answer',function(msg){
ctx.beginPath();
ctx.arc(msg.x,msg.y,20,0,Math.PI*2,true);
ctx.fill();
})
</script>
3.node server
4.访问localhost:3000
项目地址:https://github.com/lianxiHub/paint