Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive Blob in WebSocket and render as image in Canvas

I'm building a simple WebSocket application that transfers binary snapshots of the current canvas to other listeners.

The current canvas snapshot is sent using WebSocket as:

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];
}
websocket.send(buffer);

Trying to render the data on the receiving end as:

var bytes = new Uint8Array(blob.size);
var image = context.createImageData(canvas.width, canvas.height);
for (var i=0; i<image.length; i++) {
    image[i] = bytes[i];
}
context.drawImage(image, 0, 0);

The blob is received correctly but the image is still not rendered.

Any idea ?

like image 901
Arun Gupta Avatar asked Nov 15 '12 01:11

Arun Gupta


1 Answers

Setting the binaryType attribute of WebSocket right after connection initialization did the trick. This can be done as:

var wsUri = "ws://localhost:8080/whiteboard/websocket";
var websocket = new WebSocket(wsUri);
websocket.binaryType = "arraybuffer";

This would allow both text and binary data to be transfered.

like image 83
Arun Gupta Avatar answered Oct 27 '22 02:10

Arun Gupta