首页 > 代码库 > WebRTC–getUserMedia-filter

WebRTC–getUserMedia-filter

示例说明:抓取MediaStream的一帧数据,并对该帧数据使用Css滤镜效果。

步骤:

1. 由getUserMedia方法获取一个可用的MediaStream

2. canvas方法drawImage抓取MediaStream的一帧数据

3. 根据用户点击操作,对canvas元素使用滤镜效果的css样式

在webkit内核中,css滤镜有blur, grayscale, invert, sepia等

参见示例Demo

步骤:

定义滤镜,下面是相应的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画布// viewportcanvas.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 Constraintsvar 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 = http://www.mamicode.com/window.URL.createObjectURL(stream);"navigator.getUserMedia error: ", error);}navigator.getUserMedia(constraints, successCallback, errorCallback);

WebRTC–getUserMedia-filter