在 WebSocket 中接收 Blob 并在 Canvas 中呈现为图像 [英] Receive Blob in WebSocket and render as image in Canvas

查看:75
本文介绍了在 WebSocket 中接收 Blob 并在 Canvas 中呈现为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个简单的 WebSocket 应用程序,用于将当前画布的二进制快照传输到其他侦听器.

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

当前画布快照是使用 WebSocket 发送的:

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);

Blob 已正确接收,但图像仍未呈现.

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

有什么想法吗?

推荐答案

在连接初始化后立即设置 WebSocket 的 binaryType 属性就成功了.可以这样做:

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.

这篇关于在 WebSocket 中接收 Blob 并在 Canvas 中呈现为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆