0

i use html5 to create a video to loop and draw the video to canvas, i create multiple canvas and draw every part of video on each canvas, but i found out after some time, it will cause google chrome ran out of memory.

here is the code to draw video on canvas.

v.addEventListener('play', function(){
      cw = v.clientWidth * convas_rate_width;
      ch = v.clientHeight * convas_rate_height;
      canvas.width = (videoWidth/matrix_x) * canvas_location_x;
      canvas.height = (videoHeight/matrix_y) * canvas_location_y;
      back.width = cw;
      back.height = ch;


      draw(v,context,context,cw,ch,x,y,matrix_x, matrix_y);
    },false);

function draw(v,c,bc,w,h,x,y,matrix_x,matrix_y) {
    if(v.paused || v.ended) return false;
    // First, draw it into the backing canvas

    var x_coord = -((w/matrix_x) * x);
    var y_coord = -((h/matrix_y) * y);

    bc.drawImage(v,x_coord,y_coord,w,h);
    // Grab the pixel data from the backing canvas
    var idata = bc.getImageData(0,0,(w),(h));


    var data = idata.data;
    // Loop through the pixels, turning them grayscale

    idata.data = data;
    // Draw the pixels onto the visible canvas
    c.putImageData(idata,0,0);
    // Start over!
    setTimeout(draw,10,v,c,bc,w,h,x,y,matrix_x, matrix_y);
  }

Here is the printscreen : Google Chrome ran out of memory

Is there anyway to prevent looped video causing the "out of memory" error?

VC.One
  • 14,790
  • 4
  • 25
  • 57
chengwei
  • 147
  • 3
  • 16

1 Answers1

0

There is a lot of missing code so can not say where the memory is being used. Most likely you are either closing over the image data thus keeping a reference and not letting the browser delete it or you specifically make a copy of the reference, effectively doing the same thing.

Also you should not use setTimeout to show video frames. Use requestAnimationFrame

To convert to grey you dont need to get the image data you can use the composite operation to do that.

  • Displaying video in canvas shows how to display a video in the canvas.
  • Canvas filters for realtime video FX show how to get a variety of video FX (including Black and White) using the built in canvas globalCompositeOperation which is significantly quicker and uses much less memory than manually processing pixels in javascript via the imageData array.
Blindman67
  • 51,134
  • 11
  • 73
  • 136