先展示一下效果:
左边是处理前的原图,右边是经过canvas处理之后的效果。
html代码如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <canvas id="canvas" width="800" height="800"></canvas> 9 </body> 10 </html>
javascript代码如下:
1 <script type = "text/javascript"> 2 var canvas = document.getElementById(‘canvas‘); 3 var context = canvas.getContext(‘2d‘); 4 var image = new Image(); 5 image.src = "img/7.jpg"; 6 image.onload = function(){ 7 context.drawImage(image,0,0,300,500); 8 var imageData = context.getImageData(0,0,300,500); 9 //获取到每个像素的信息 10 var px = imageData.data; 11 for(var i = 0; i < px.length; i+=4){ 12 var r = px[i]; 13 var g = px[i + 1]; 14 var b = px[i + 2]; 15 var gray = ((r + g + b)/3); 16 px[i] = gray; 17 px[i + 1] = gray; 18 px[i + 2] = gray; 19 } 20 context.putImageData(imageData,300,0); 21 } 22 </script>
canvas实现对画面的修改说的简单一些就是将一个一个像素点从新赋值画上去,最后展示在面前的就是一幅经过修改的画面。同理我们如果对视频进行这样的修改呢,我们知道视频就是一张一张图片组成的,如果我们将每一张图片都做这样的修改是不是也能的到这样的效果。下面的代码是对视频的修改。
html代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <canvas id="canvas" width="800" height="800"></canvas> 9 <video src="ganggang.mp4" id="video"></video> 10 </body> 11 </html>
javascript代码:
1 <script type="text/javascript"> 2 var canvas = document.getElementById(‘canvas‘); 3 var context = canvas.getContext(‘2d‘); 4 var video = document.getElementById(‘video‘); 5 function animate(){ 6 if(!video.end){ 7 context.drawImage(video,0,0,200,300); 8 var imageData = context.getImageData(0,0,200,300); 9 var px = imageData.data; 10 for(var i = 0; i < px.length; i+=4){ 11 var r = px[i]; 12 var g = px[i+1]; 13 var b = px[i+2]; 14 var gray = ((r+g+b)/3); 15 px[i] = gray; 16 px[i+1] = gray; 17 px[i+2] = gray; 18 } 19 context.putImageData(imageData,200,0); 20 window.requestAnimationFrame(animate); 21 } 22 } 23 video.oncanplay = function(){ 24 video.play(); 25 window.requestAnimationFrame(animate); 26 } 27 </script>
最后的效果这里就不展示了。
时间: 2024-10-11 15:50:04