效果图:
注:本例需在服务器上运行的才能看到效果、视频文件可换成本地视频(HBuilder有集成服务器或者使用wampmanager)。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas</title>
<style type="text/css">
#canv{
border:1px solid red;
}
</style>
</head>
<body> <video id="sourcevid" autoplay="true" loop="true">
<source src="BigBuckBunny_640x360.mp4" type="video/mp4"/>
<source src="BigBuckBunny_640x360.ogv" type="video/ogg"/>
</video>
<canvas id="canv" width="640" height="360"></canvas>
<script type="text/javascript">
var canv=document.getElementById('canv');
var video=document.getElementById('sourcevid');
var ctx=canv.getContext("2d");
function run(){
//在画布里绘制出sourcevid
ctx.drawImage(video,0,0);
window.requestAnimationFrame(run);
var imageData = ctx.getImageData(0,0,400,400);
var d = imageData.data;//保存的是红绿蓝透明度的通道的值
for(var i = 0; i < d.length; i += 4) {
var verage = (d[i] + d[i+1] + d[i+2])/3;
var verage1 = 0.299 * d[i] + 0.587 * d[i+1] + 0.114 * d[i+2]
d[i] = d[i+1] = d[i+2] = verage1;
}
// putImageData() 将图像数据放回画布
ctx.putImageData(imageData,0,0);
}
run();
</script>
</body>
</html>