首页 > 代码库 > WebRTC–getUserMedia & Canvas

WebRTC–getUserMedia & Canvas

下面是一个使用getUserMedia接口和Canvas的drawImage方法实现的截图功能(截取视频中的一帧)。

基本思路是这样子的

  1. getUserMedia获取一个MediaStream, stream
  2. stream作为video的输入源
  3. 提供一个button按钮。当用户点击时,使用canvas的drawImage方法绘制video的一帧数据

源代码位于gitlab上

index.html代码

<!DOCTYPE html><html><head><meta name="keywords" content="WebRTC, HTML5, JavaScript" /><meta name="description" content="WebRTC Demo." /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="chrome=1" /><base target="_blank"><title>getUserMedia to canvas - Snapshot</title><link rel="stylesheet" href="http://www.mamicode.com/css/main.css" /></head><body><div id="container">  <h1><a href="http://www.mamicode.com/#" title="WebRTC Demo homepage">WebRTC Demo</a> <span>getUserMedia to canvas - 拍照</span></h1>  <video autoplay></video>  <button>拍照</button>  <canvas></canvas>  <p>使用canvas元素的<code>drawImage()</code>方法绘制video元素的一帧数据。</p>  <p><code>canvas</code>, <code>video</code> and <code>stream</code>三个变量是全局的,用户可以从console中查看。</p>  <a href="http://www.mamicode.com/#" title="在gitlab上查看源代码" id="viewSource">查看源代码-gitlab.baidu.com</a>  </div>  <script src="http://www.mamicode.com/js/main.js"></script></body></html>

main.js代码

// 全局变量button = document.querySelector("button");video = document.querySelector("video");canvas = document.querySelector("canvas");canvas.width = 480;canvas.height = 360;// 点击事件处理// 在canvas上画一帧画像button.onclick = function(){  canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);}navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;var constraints = {audio: false, video: true};var video = document.querySelector("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);
 

drawImage方法定义如下:

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

img - 规定要使用的图像、画布或视频

sx - 开始剪切的x位置

sy - 开始剪切的y位置

swidth - 被剪切的宽度

sheight - 被剪切的高度

WebRTC–getUserMedia & Canvas