问题描述:

I've got a following problem: I want to send canvas element over sockets using socket.io and Node.js. I've created below (pseudo)code:

var myCanvas = document.getElementById("myCanvas");

var ctx = myCanvas.getContext("2d");

// open sockets connection, join to the room etc.

socket.on('message', function(message) {

alert(message.canvas);

});

$(myCanvas).mouseup(function(e) {

socket.emit('message', {

canvas: myCanvas,

});

});

Unfortunately, the second peer doesn't receive a message, first received this error:

Uncaught RangeError: Maximum call stack size exceeded

from socket.io.js file, line 5380

Thanks for any help

网友答案:

You can't emit a DOM element (your myCanvas).

Socket.IO works by serializing whatever it's sending (largely using JSON serialization). But a canvas element cannot be serialized.

You will have to serialize the canvas content in order to emit it. For example, you could use myCanvas.toDataURL() to create a dataURL (string) representing the canvas content.

Then on the listening side, you will:

  • receive the dataURL,
  • convert the dataURL into a new Image object,
  • use context.drawImage to draw the new image object onto the receiver's canvas.
相关阅读:
Top