在服务器上: 我正在加载一个png图像:
var myimage = png.load('test.png');
then sending over websocket connection:
ws.send(myimage);
在客户端:
function onMessage(evt) {
if (evt.data instanceof ArrayBuffer) {
var length = evt.data.byteLength;
var bytes = new Uint8Array(evt.data);
var image = document.getElementById("image");
var img = new Image();
img.src = 'data:image/png;base64,'+ window.btoa(bytes);
var ctx = image.getContext("2d");
ctx.drawImage(img, 0, 0);
}
没有在画布上显示任何内容。关于我做错了什么的任何想法?
答案 0 :(得分:2)
尝试创建blob并将其转换为blob网址
function onMessage(evt) {
if (evt.data instanceof ArrayBuffer) {
var length = evt.data.byteLength;
var blob = new Blob([evt.data],{type:'image/png'});
var url = URL.createObjectURL(blob);
var image = document.getElementById("image");
var img = new Image();
img.onload = function(){
var ctx = image.getContext("2d");
ctx.drawImage(img, 0, 0);
}
img.src = url;
}