Draw video on canvas HTML5

后端 未结 3 915
感情败类
感情败类 2021-02-06 03:30

I\'m trying to draw a video on a canvas. To achieve this I capture the onMouseDown and onMouseUp events in Javascript to get the x and y coordinates of each event (that I need t

3条回答
  •  深忆病人
    2021-02-06 03:32

    You need to set up a continuous rendering. You are only rendering the first frame of the video. Canvas is dumb and does not know about videos. You have just dumped pixels from the video onto the canvas. You need to update the canvas continuously.

    The best way is to use requestAnimationFrame this makes sure everything is synced up with the browsers own rendering.

    In the example below the rendering is started when the video is loaded. Be sure to end the previous updates if you load a second video.

    var canvas = document.getElementById("canV");
    var ctx = canvas.getContext("2d");
    
    var video = document.createElement("video");
    video.src = "http://techslides.com/demos/sample-videos/small.mp4";
    video.addEventListener('loadeddata', function() {
      video.play();  // start playing
      update(); //Start rendering
    });
    
    
    
    
    function update(){
      ctx.drawImage(video,0,0,256,256);   
      requestAnimationFrame(update); // wait for the browser to be ready to present another animation fram.       
    }
    #canV {
      width:256px;
      height:256px;
    }

提交回复
热议问题