无法在通过Python WebSocket接收的画布上绘制图像

时间:2018-05-04 04:31:02

标签: javascript python websocket html5-canvas

我想通过Python WebSocket传输图像以在HTML画布上绘制。客户端程序使用JavaScript实现,该JavaScript使用HTML canvas标签。服务器端程序是用Python编写的。

客户端:

<activity
        android:name=".activities.Activity2"
        android:theme="@style/AppTheme.NoActionBar" />
<activity android:name=".activities.TestActivity"/>

服务器:

var ws = new WebSocket("ws://127.0.0.1:5678/");
ws.binaryType = "arraybuffer";
var canvas = document.getElementById('canvasOutput'); 
var context=canvas.getContext("2d"); 

var img = new Image();

// show loading notice


ws.onmessage= function (data) {
    console.log(data);
    //var blobdata = data.data;
    //console.log(blobdata); 
    //var uint8Arr = new Uint8Array(data.data);
    //console.log(uint8Arr);
    var base64 = btoa(new Uint8Array(data.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
    //var str = String.fromCharCode.apply(null, uint8Arr);
    //var base64String = btoa(uint8Arr);
    //console.log(base64String);
    //  context.fillRect(0, 0, 80, 100);    
    img.onload = function () {
        console.log(img);
        context.drawImage(this, 0, 0, canvas.width, canvas.height);
    };
    img.src = "data:image/png;base64," +base64;
    console.log(img);
    //context.drawImage(img,0,0,canvas.width,canvas.height);
};

图像数据已传输到客户端,但未在画布上打印。任何人都可以告诉我我错在哪里,我尝试了各种选择,但没有一个能奏效。这是我的浏览器的控制台图像。

收到的数据的控制台输出和img.src:

Console output of the data received and img.src

0 个答案:

没有答案