效果如下:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>canvas绘制视频</title>
<script type="text/javascript">
window.onload = function () {
// 1.canvas从视频上绘制图像
var video = document.getElementById('video');
var myCanvas = document.getElementById('myCanvas');
var ctx = myCanvas.getContext('2d');
// 播放
video.addEventListener('play', function () {
var i = window.setInterval(function () {
ctx.drawImage(video, 0, 0, 270, 135);
}, 20); // 每0.02秒画一张图片
}, false);
// 暂停
video.addEventListener('pause', function () {
window.clearInterval(i); // 暂停绘画
}, false);
// 结束
video.addEventListener('ended', function () {
clearInterval(i);
}, false)
// 绘制文本
// ctx.font = "18px Georgia";
// ctx.strokeText("测试测试!", 0, 18);
// 2.canvas绘制图像
var cv1 = document.getElementById("cv1")
var ctx1 = cv1.getContext('2d');
var img = document.getElementById('img')
ctx1.drawImage(img, 5, 5)
}
</script>
</head>
<body>
<h3 style="color:red">1.视频如下:</h3>
<video id="video" controls width="270" autoplay>
<source src="http://www.w3school.com.cn/example/html5/mov_bbb.mp4" type='video/mp4'>
<source src="http://www.w3school.com.cn/example/html5/mov_bbb.ogg" type='video/ogg'>
<source src="http://www.w3school.com.cn/example/html5/mov_bbb.webm" type='video/webm'>
</video>
<h4>canvas从视频上绘制图像</h4>
<canvas id="myCanvas" width="270" height="135" style="border:1px solid red;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<h3 style="color:red">2.图像如下:</h3>
<img src="flower.jpg" id="img" width="400" height="266" alt="">
<h4>canvas绘制图像</h4>
<canvas id="cv1" width="410" height="276" style="border:1px solid red;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</body>
</html>