Play video on canvas and preserve the last frame/image on canvas

半城伤御伤魂 提交于 2019-12-10 19:58:19

问题


I'm using the following script code to draw a video on canvas:

$("#vPlayer").on('play', function (e) {
           var canvas = $('canvas')[0];
           var ctx = canvas.getContext('2d');
           var $this = this;
           canvas.width = 640;
           canvas.height = 480;
           (function loop() {
               if (!$this.paused && !$this.ended) {
                   ctx.drawImage($this, 0, 0, 640, 480);
                   setTimeout(loop, 1000 / 30); // drawing at 30fps
               }
           })();

});

The code works well, but in my case, I want to change the video source (src attribute) of the video tag every 2 mins. When I set the src attr for the video and during the loading time for the video, the canvas displays white screen. How can I preserve the last image of video and do not clear the canvas?

It is a little bit weird, because when I don't set the width and height for the canvas, the last frame is preserved, but I need to set the size.

Thanks in advanced.


回答1:


Every time you set the size of the canvas it will be cleared.

To avoid this you need to set the size at the "beginning", before you start drawing to it. In this case I would recommend you set it outside your event handler as well as the initializing of the canvas and context variable:

var canvas = $('canvas')[0];
var ctx = canvas.getContext('2d');
canvas.width = 640;
canvas.height = 480;

$("#vPlayer").on('play', function (e) {
   var $this = this;
   (function loop() {
       if (!$this.paused && !$this.ended) {
           ctx.drawImage($this, 0, 0, 640, 480);
           setTimeout(loop, 1000 / 30); // drawing at 30fps
       }
   })();
});


来源:https://stackoverflow.com/questions/20249529/play-video-on-canvas-and-preserve-the-last-frame-image-on-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!