Pedro
Pedro

Reputation: 69

Share uploaded image to canvas between multiple users

I am doing a collaborative app with node and sockets where I can upload images to canvas. If one of the connected users uploads a image, how can I make that image to be drawn to all the connected users?

This is what i tried:

Client

socket.on('img', 
        function() {
        console.log("Image uploaded");
        ctx.drawImage(img, 105, 50);
        }
    );

function el(id){return document.getElementById(id);}
    function readImage() {
        if ( this.files && this.files[0] ) {
            var FR= new FileReader();
            FR.onload = function(e) {
               var img = new Image();
               img.onload = function() {
                   var image = ctx.drawImage(img, 105, 50);
                   console.log("sendimg: ");
                   socket.emit('img');
               };
               img.src = e.target.result;
            };       
            FR.readAsDataURL( this.files[0] );
        }
    }
    el("fileUpload").addEventListener("change", readImage, false);

Server

socket.on('img',
      function() {
      console.log("Image Uploaded");
        socket.broadcast.emit('img');
      }
    );

Upvotes: 0

Views: 105

Answers (1)

Rob M.
Rob M.

Reputation: 36511

When you emit, you need to send the image data along as well. For example, you could send a base64 encoded version of the image:

img.onload = function() {
   var image = ctx.drawImage(img, 105, 50);
   console.log("sendimg: ");
   socket.emit('img', ctx.toDataURL());
};

You can then add an image with the src set to that data URL. Different image formats are available if you prefer

You then need to update your client to handle the parameter:

socket.on('img', function(dataURL) {
    console.log("Image uploaded");
    var img = new Image;
    img.onload = function(){
      ctx.drawImage(img, 105, 50);
    };
    img.src = dataURL;

});

And your server to pass it along:

socket.on('img', function(dataURL) {
    console.log("Image Uploaded");
    socket.broadcast.emit('img', dataURL);
});

Upvotes: 1

Related Questions