Video: WebRTC canvas to video

WebRTC from canvas to video over two tabs

HTML

<h1>Video</h1>
<h4>Video element gets stream from canvas</h4>
<button id="button" onclick="connect()">Connect</button>
<div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="https://rawgit.com/jan-ivar/localSocket/master/localSocket.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js"></script>
<video autoplay></video>

JavaScript

var video = document.querySelector('video');

video.addEventListener('loadedmetadata', function() {
  console.log('Remote video videoWidth: ' + this.videoWidth +
    'px,  videoHeight: ' + this.videoHeight + 'px');
});

video.onresize = function() {
   console.log('Remote video size changed to ' +
    video.videoWidth + 'x' + video.videoHeight);
  // We'll use the first onsize callback as an indication that video has started
  // playing out.
  if (startTime) {
    var elapsedTime = window.performance.now() - startTime;
     console.log('Setup time: ' + elapsedTime.toFixed(3) + 'ms');
    startTime = null;
  }
};
function gotRemoteStream(e) {
console.log('rrr')
  if (video.srcObject !== e.streams[0]) {
    video.srcObject = e.streams[0];
    trace('pc2 received remote stream');
  }
}

var pc = new RTCPeerConnection(), dc, enterPressed = e => e.keyCode == 13;
pc.ontrack = gotRemoteStream;

var connect = () => init(dc = pc.createDataChannel("chat"));
pc.ondatachannel = e => init(dc = e.channel);

var init = dc => {
  dc.onopen = e => (dc.send("Hi!"), chat.select());
  dc.onclose = e => log("Bye!");
  dc.onmessage = e => log(e.data);
};

pc.oniceconnectionstatechange = e => log(pc.iceConnectionState);
pc.onicecandidate = e => send({ candidate: e.candidate });
pc.onnegotiationneeded = e => pc.createOffer()
  .then(offer => pc.setLocalDescription(offer))
  .then(() => send({ sdp: pc.localDescription }))
  .catch(log);

var sc = new localSocket(), send = obj => sc.send(JSON.stringify(obj));
var incoming = msg => msg.sdp &&
  pc.setRemoteDescription(new RTCSessionDescription(msg.sdp))
  .then(() => pc.signalingState == "stable" || pc.createAnswer()
    .then(answer => pc.setLocalDescription(answer))
    .then(() => send({ sdp: pc.localDescription })))
  .catch(log) || msg.candidate &&
  pc.addIceCandidate(new RTCIceCandidate(msg.candidate)).catch(log);
sc.onmessage = e => incoming(JSON.parse(e.data));

var log = msg => div.innerHTML += "<br>" + msg;