Canvas 播放视频

Canvas 图像来源 CanvasImageSource 章节中我们有提到可以使用 HTMLVideoElement 作为 drawImage() 的图像来源

我突然间灵光一闪,其实我们可以使用 Canvas 做一个简易的视频播放器

你可以先点击下面的按钮看看


   


全部代码如下

<!DOCTYPE html>
<meta charset="utf-8"> 
<div style="border:1px solid #eee">
<canvas id="canvas-1" width="500" height="300">
</canvas>
<br/>
&nbsp;&nbsp;&nbsp;<input type="button" value="播放"  id="play" />
<input type="button" value="暂停"  id="stop" />
<br/><br/>
</div>
<script>
var timer = null;
var video = document.createElement("video");
var canvas = document.getElementById("canvas-1");
var ctx = canvas.getContext("2d");


function drawTip(text) {
    canvas.width  = canvas.width;
    canvas.height = canvas.height;
    ctx.font = "24px Microsoft YaHei";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText(text,canvas.width/2,canvas.height/2);
}

function init() {
    drawTip("正在缓冲中....");
    video.src = "https://www.twle.cn/static/i/html/html_video_2.mp4"
}

video.oncanplay = function() {
    drawTip("加载完毕,开始播放")
}

function play() {
    init();
    video.play();
    timer = setInterval(function(){
      if(video.currentTime >= video.duration){
        stop();
      };
      ctx.drawImage(video, (canvas.width-video.videoWidth)/2, (canvas.height-video.videoHeight)/2, video.videoWidth, video.videoHeight);//绘制视频
   },16);
}

function stop(){
    clearInterval(timer);
    video.pause();
}

drawTip("你可以点击播放按钮播放视频....")
document.getElementById("play").onclick = function(){ play();}
document.getElementById("stop").onclick = function(){ stop();}
</script>

代码很简单,关于 <video> 的属性和方法,可以访问我们的 HTML 音频/视频 DOM 参考手册

drawImage(video)

当我们调用 drawImage(video) 时绘制的是当前 video 的画面

因为 video 一直在播放,所以我们要设置一个定时器,将 video 的当前帧绘制到画布上

video.play();
timer = setInterval(function(){
  if(video.currentTime >= video.duration){
    stop();
  };
  ctx.drawImage(video, (canvas.width-video.videoWidth)/2, (canvas.height-video.videoHeight)/2, video.videoWidth, video.videoHeight);//绘制视频
},16);

大家可以在视频播放时点击暂停按钮,看看效果

另外,videoWidthvideoHeight 属性是获取视频本身的长和宽

Canvas 基础教程

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.