下面是一个使用getUserMedia接口和Canvas的drawImage方法实现的截图功能(截取视频中的一帧)。
基本思路是这样子的:
- getUserMedia获取一个MediaStream, stream
- stream作为video的输入源
- 提供一个button按钮。当用户点击时,使用canvas的drawImage方法绘制video的一帧数据
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="../css/main.css" /> </head> <body> <div id="container"> <h1><a href="#" 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="#" title="在gitlab上查看源代码" id="viewSource">查看源代码-gitlab.baidu.com</a> </div> <script src="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 = window.URL.createObjectURL(stream); } else { video.src = stream; } } function errorCallback(error){ console.log("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 - 被剪切的高度
时间: 2024-11-10 00:57:56