0

Context: I am creating a web app where I can draw on the canvas, save that as an image, and send it to another client via Node.

What works:

  • Drawing (on either client. It is updated in real time).
  • Saving canvas as a Uint8Array
  • Saving canvas as an img div w/ base64 encoded image

Where I'm stuck:

I can't seem to pipe the finished image to other clients. I'm able to save the canvas in a variety of ways, but not sure of how to get it across.

How I'm sending it to the node server as a div:

   byId('sendHTML').onclick = SendImageHTML;  
   function SendImageHTML() {    
        var imageHTML = convertCanvasToImage(canvas); 
        socket.emit('SendImageHTML', imageHTML);
        // EMITS: <img src="data:image/png;base64, iVB9023423523345346....."
   }

Sending as a Uint8Array:

  /**
   * Converts canvas to bytes & emits web socket message
   * @return {Uint8Array} Bytes from canvas 
   */     
  byId('defImgBinary').onclick = DefineImageBinary;  
  function DefineImageBinary() {
        var image  = context.getImageData(0, 0, canvas.width, canvas.height);
        var buffer = new ArrayBuffer(image.data.length);
        var bytes  = new Uint8Array(buffer);

        for (var i=0; i<bytes.length; i++) {
            bytes[i] = image.data[i];
        }

        socket.emit('defImgBinary', bytes);
        // EMITS: [24, 24, 29, 255, 24, 24, 29, 255, 24, 24.......]

  }

And here is my server code:

socket.on('SendImageHTML', function (html) {
    console.log("SendImageHTML called: ");
    log(html);
    // RETURNS:
    // SendImageHTML called:
    // {} 
});




socket.on('defImgBinary', function (bytes) {
    log("defImgBinary called: ");
    log(bytes);
    // RETURNS:
    // defImgBinary called:
    // '53721': 220,
    // '53722': 219,
    // '53723': 255,
    // '53724': 229,
});

What I need help with:

What do I do with it from there? How do I actually display this as an image on the other clients?

1
3

Would that be satisfactory for you, if you'd use getDataURL() from the Canvas API and then send a base64 encoded image or a rendered DOM element?

On the client side:

You can obtain base64-encoded data from your canvas via HTMLCanvasElement.toDataURL . That will result in a String starting with data:image/png;base64..., just as in your code sample.

When you obtain the string, you can either send it directly to the server as a String, or render it into an Image element:

var image = new Image(width, height);
image.src = myBase64String;

image.addEventListener('load', function () { /* NOTE On image loaded */ });

If you want to send a rendered DOM Element to the server, you will probably find Element.outerHTML very useful - this property will return an exact string representation of the element (ex. "<img src="data:image/png;base64..." width="256" height="256" />").

On the server side:

In both cases, you can simply send the data through to the other clients via their sockets.

On the other clients' side:

If you send a simple base64 encoded string, it can be easily rendered using an Image element:

var image = new Image(256, 256);
image.src = receivedBase64String;

image.addEventListener('load', function () { 
  document.appendChild(image);
});

If you send an already rendered element, you can put it into the DOM structure using document.createElement:

var image = document.createElement('div'); // NOTE Create a 'host' element
image.innerHTML = receivedRenderedElementString;

document.appendChild(image);

Example:

Please see the code attached below for a working example.

Client side:

<title>
  Canvas Sample
</title>
<p>
  <canvas id="sample-canvas" width="256" height="256"></canvas>
</p>
<p>
  <button id="send-canvas">
    Send canvas
  </button>
  <label for="send-as-div">
    <input type="checkbox" id="send-as-div">
      Send as div
    </input>
  </label>
</p>
<p id="output-console"></p>

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
  // NOTE Simple IO console element for socket communication
  let outputConsole = document.querySelector('#output-console');
  let printToConsole = (text = '') => {
    outputConsole.innerHTML += text + '<br/>';
  };
  let renderToConsole = (element) => {
    outputConsole.appendChild(element);
    outputConsole.innerHTML += '<br/>';
  };

  // NOTE Load image (random cat image)
  let image = new Image(250, 250);
  image.src = 'http://thecatapi.com/api/images/get?format=src&size=small';
  printToConsole('Image loading.');

  // NOTE Setup canvas
  // Render the cat image when it is loaded.
  let canvas = document.querySelector('#sample-canvas');
  let context = canvas.getContext('2d');

  image.addEventListener('load', () => {
    context.drawImage(image, 0, 0);
    printToConsole('Image loaded.');
  });

  image.addEventListener('error', (error) => {
    printToConsole('Image error.' + JSON.strinfify(error));
  });

  // NOTE Setup a websocket
  // Socket will allow to send 'img' message with either a base64 encoded
  // image data, or a rendered HTML Image element.
  let socket = io('ws://localhost:8080/');

  socket.on('error', (error) => {
    printToConsole('Socket error.' + JSON.stringify(error));
  });

  socket.on('img', (image) => {
    let renderedImage = null;

    if (image.indexOf('data:image/') === 0) {

      // NOTE If we receive a base64 image, we render it as an Image
      renderedImage = new Image(250, 250);
      renderedImage.src = image;
    } else {

      // NOTE If we receive a rendered <img> element, we render it directly
      // via document.createElement
      renderedImage = document.createElement('div');
      renderedImage.innerHTML = image;
    }

    printToConsole('Received image.');
    renderToConsole(renderedImage);
  });

  // NOTE Setup button
  let sendButton = document.querySelector('#send-canvas');

  sendButton.addEventListener('click', () => {
    let encodedCanvas = canvas.toDataURL();
    let sendAsDiv = document.querySelector('#send-as-div').checked;
    let payload = null;

    if (sendAsDiv) {
      let imageElement = new Image(250, 250);
      imageElement.src = encodedCanvas;

      payload = imageElement.outerHTML;
    } else {
      payload = encodedCanvas;
    }

    socket.emit('img', payload);

    printToConsole('Image sent.');
  });
</script>

Server side (requires npm install -D express socket.io):

'use strict';

let express = require('express');
let http = require('http');
let socketIo = require('socket.io');

// NOTE Setup server
let httpServer = http.createServer(express());
let socketServer = socketIo(httpServer);
let sockets = [];
let port = 8080;

httpServer.listen(port);

// NOTE Setup socket listener

socketServer.on('connection', (socket) => {
  sockets.push(socket);

  let socketId = sockets.length;

  socket.on('img', (payload) => {
    socket.broadcast.emit('img', payload);
  });
});

Let me know if that solves your issue 🙂

2
  • 1
    Upvoted for mentioning base64 representation of the image for connected clients to consume. – Alex Sep 27 '16 at 1:08
  • Worked like a charm! I was making this way more complicated than it needed to be. Thanks for the thorough response, and for offering two solutions! – Dave Voyles Sep 27 '16 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.