var video =document.getElementById('video');functiongrabWebCamVideo() {console.log('Getting user media (video) ...');navigator.mediaDevices.getUserMedia({ audio:false, video:true }).then(gotStream).catch(function(e) {alert('getUserMedia() error: '+e.name); });}
当用户单击“捕捉”按钮时,从视频流中获取快照(视频帧),并将其显示在画布元素中:
var photo =document.getElementById('photo');var photoContext =photo.getContext('2d');functionsnapPhoto() {photoContext.drawImage(video,0,0,photo.width,photo.height);show(photo, sendBtn);}
当用户单击发送按钮时,将图像转换为字节并通过数据通道发送:
functionsendPhoto() {// Split data channel message in chunks of this byte length.varCHUNK_LEN=64000;var img =photoContext.getImageData(0,0, photoContextW, photoContextH), len =img.data.byteLength, n = len /CHUNK_LEN|0;console.log('Sending a total of '+ len +' byte(s)');dataChannel.send(len);// split the photo and send in chunks of about 64KBfor (var i =0; i < n; i++) {var start = i *CHUNK_LEN, end = (i +1) *CHUNK_LEN;console.log(start +' - '+ (end -1));dataChannel.send(img.data.subarray(start, end)); }// send the reminder, if anyif (len %CHUNK_LEN) {console.log('last '+ len %CHUNK_LEN+' byte(s)');dataChannel.send(img.data.subarray(n *CHUNK_LEN)); }}
接收端将数据信道消息字节转换回图像并将图像显示给用户:
functionreceiveDataChromeFactory() {var buf, count;returnfunctiononmessage(event) {if (typeofevent.data ==='string') { buf =window.buf =newUint8ClampedArray(parseInt(event.data)); count =0;console.log('Expecting a total of '+buf.byteLength +' bytes');return; }var data =newUint8ClampedArray(event.data);buf.set(data, count); count +=data.byteLength;console.log('count: '+ count);if (count ===buf.byteLength) {// we're done: all data chunks have been receivedconsole.log('Done. Rendering photo.');renderPhoto(buf); } };}functionrenderPhoto(data) {var canvas =document.createElement('canvas');canvas.width = photoContextW;canvas.height = photoContextH;canvas.classList.add('incomingPhoto');// trail is the element holding the incoming imagestrail.insertBefore(canvas,trail.firstChild);var context =canvas.getContext('2d');var img =context.createImageData(photoContextW, photoContextH);img.data.set(data);context.putImageData(img,0,0);}