WebRTC–getUserMedia-filter
示例说明:抓取MediaStream的一帧数据,并对该帧数据使用Css滤镜效果。
步骤:
1. 由getUserMedia方法获取一个可用的MediaStream
2. canvas方法drawImage抓取MediaStream的一帧数据
3. 根据用户点击操作,对canvas元素使用滤镜效果的css样式
在webkit内核中,css滤镜有blur, grayscale, invert, sepia等
步骤:
定义滤镜,下面是相应的CSS代码(以下滤镜为webkit内核提供的)
<style> .blur { -webkit-filter: blur(3px); } .grayscale { -webkit-filter: grayscale(1); } .invert { -webkit-filter: invert(1); } .sepia { -webkit-filter: sepia(1); } button { width: 8.1em; } button#snapshot { margin: 0 1em 1em 0; } </style>
页面代码
<video autoplay></video> <button id="snapshot">截图</button> <button id="filter">使用滤镜</button> <canvas></canvas>
js代码
snapshotButton = document.querySelector("button#snapshot"); //截图按钮 filterButton = document.querySelector("button#filter"); //滤镜铵钮 video = document.querySelector("video"); //video标签 canvas = document.querySelector("canvas"); //canvas画布 // viewport canvas.width = 480; canvas.height = 360; // 滤镜数组 var filters = ['blur', 'grayscale', 'invert', 'sepia']; // 截图 snapshotButton.onclick = function snap(){ canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height); } // 应用滤镜(循环使用) filterButton.onclick = function(){ var newIndex = (filters.indexOf(canvas.className) + 1) % filters.length; canvas.className = filters[newIndex]; } navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; // WebRTC Constraints var constraints = {audio: false, video: true}; var video = document.querySelector("video"); // MediaStream作为video的输入 function successCallback(stream){ window.stream = stream; // stream available to console if (window.URL) { video.src = window.URL.createObjectURL(stream); } else { video.src = stream; } } function errorCallback(error){ console.log("navigator.getUserMedia error: ", error); } navigator.getUserMedia(constraints, successCallback, errorCallback);