Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
First stream freezes after seccond connection opens?

I'm constructing an application that allows multiple devices to stream their webcam, through the browser, to another device. Each streaming device takes a DataURL image from the webcam and sends it over WebSocket to a server, which will then distribute the array of images to viewers. The viewer will parse the message and display each image on its own individual <canvas>.

It works fine when one user is streaming, but when a second device begins to stream, the first one freezes. It appears the last image in the array is the only one to actually be rendered.

I've been reviewing this code for several hours and can't understand what I'm missing here.

var socket = new WebSocket("wss://my_server:8443");


socket.onmessage = function(msg) {
  //parse the incoming message into a usable array
  msg = JSON.parse(msg.data);

  var div = document.getElementById("streams");
  
  //for every incoming stream
  for (var i in msg) {
    //create a new Image, then render it onto a canvas element.
    var img = new Image();
    img.onload = function() {
      //if there isn't a canvas element to render it onto already, create one (for when a stream is created)
      if (document.getElementById(i) == null) {
        var c = document.createElement("canvas");
        c.width = img.width;
        c.height = img.height;
        c.setAttribute("id", i);
        div.appendChild(c);
      }
      //draw the image onto the canvas
      var canvas = document.getElementById(i);
      var ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0);
    }
    //set the Data URL as the image's SRC
    img.src = msg[i];
  }
}

I originally just added <img> elements to the <div>, but it ended up taking too long to load, creating short flashes in between each frame.

What's wrong with my code? It seems to freeze all active streams except for the one most recently started (last in the array).

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!