我正在尝试使用Web-RTC数据通道将图像文件发送给另一个对等方。 我成功将图像的所有字节发送给另一个对等方,但是我无法将图像渲染到我的canvas元素。 这是我的发件人代码:
imageUpload = (event) =>
{
console.log("image event occured");
if (event.target.files && event.target.files[0])
{
var reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // read file as data url
reader.onload = (event: any) => {
var canvas = <HTMLCanvasElement>document.getElementById("canvas3");
var context = canvas.getContext('2d');
var base_image = new Image();
base_image.src = event.target.result;
base_image.onload = function () {
context.drawImage(base_image, 0, 0);
}
this.image = context.getImageData(0, 0, 200, 200);
console.log(this.image.data);
}
setTimeout(() => {
this.sendimage();
}, 2000);
}
}
sendimage() {
var CHUNK_LEN = 64000;
var len = this.image.data.byteLength,
n = len / CHUNK_LEN | 0;
console.log(n);
console.log('Sending a total of ' + len + ' byte(s)');
this.dataChannel.send(len);
// split the photo and send in chunks of about 64KB
for (var i = 0; i < 3; i++) {
var start = i * CHUNK_LEN,
end = (i + 1) * CHUNK_LEN;
console.log(start + ' - ' + (end - 1));
this.dataChannel.send(this.image.data.subarray(start, end));
}
首先,我将图像上传到我的画布上,然后将其发送给另一个同伴。接收方代码是这样的:
channel.onmessage = (event) => {
console.log("Arrived at on message at chrome factory")
if (typeof event.data === 'string') {
this.buf = new Uint8ClampedArray(parseInt(event.data));
console.log("buff is " + this.buf);
this.count = 0;
console.log('Expecting a total of ' + this.buf.byteLength + ' bytes');
return;
}
var data = new Uint8ClampedArray(event.data);
this.buf.set(data, this.count);
this.count += data.byteLength;
console.log('count: ' + this.count);
if (this.count === this.buf.byteLength) {
// we're done: all data chunks have been received
console.log('Done. Rendering photo.' + this.buf);
this.renderPhoto(this.buf);
}
}
renderPhoto = (data) => {
console.log("rendering");
this.canvas3 = <HTMLCanvasElement>document.getElementById('canvas3');
this.canvas3.width = 200;
this.canvas3.height = 200;
this.canvas3.classList.add('incomingPhoto');
// trail is the element holding the incoming images
var trail = document.getElementById('trail');
trail.insertBefore(this.canvas3, trail.firstChild);
this.context3 = this.canvas3.getContext("2d");
var img = this.context3.createImageData(200, 200);
img.data.set(data);
console.log("image data " + img.data.byteLength);
this.context3.putImageData(img, 0, 0);
console.log("rendered");
}
我的接收方html代码是:
div id =“传入”
h2收到的照片/ h2
div id =“ trail” / div
/ div
img id =“ comingimage”
canvas id =“ canvas3” style =“ border:淡蓝色;”
/画布
任何人都可以帮助我解决这个问题,或者任何人都可以告诉我另一种解决方案。 在此先感谢!!!