Saturday, 1 April 2017

Collaborative Paint App

I am in the early stages of learning nodejs client/server programming, for my first application I just want to make a simple collaborative drawing app like paint. So far I have this code and the only thing that seems to work is that my click properly calls in my console.log but no rectangle draws at the click location. Any help? I am pretty new to this.

var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
        
        SOCKET_LIST[socket.id] = socket;
        
        var self = {
                x:0,
                y:0,
                cx:0,
                cy:0,
        }
        
        socket.on('mousePos', function(data){
                self.x = data.x;
                self.y = data.y;
                //console.log('x:' + self.x + ' y:' + self.y);
        });
        
        socket.on('mouseClick', function(data){
                self.cx = data.x;
                self.cy = data.y;
                console.log('x:' + self.cx + ' y:' + self.cy);
        });
        
        socket.emit('paint', {x:self.cx, y:self.cy}); 
        
        /*for (var i in SOCKET_LIST){
                var socket = SOCKET_LIST[i];
                socket.emit('paint', {x:self.cx, y:self.cy}); 
        }*/
        
});
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>

<div id="gameCanvasDiv">
        <canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
</div>
        
<script>
        var socket = io();
        
        var ctx = document.getElementById("ctx").getContext("2d");
        
        ctx.fillStyle = "#FF0000";
        
        setInterval(function(){
                
                
    },40);
        
        document.onmousedown = function(event){
                
                socket.emit('mouseClick', {x:event.clientX, y:event.clientY});
        
        }
        
        document.onmouseup = function(event){
                
                socket.on('paint', function(data){
                        ctx.fillRect(data.x,data.y,10,10);
                });
                
        }
        
        document.onmousemove = function(event){
        socket.emit('mousePos', {x:event.clientX, y:event.clientY});
    }

</script>


via Jaekx

No comments:

Post a Comment