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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With