这是一项新技术。Yoy 必须有 Firefox/Chrome/Opera 浏览器并且必须更新。然后,试试这个:
function showCamera() { var streaming = false,
video = window.content.document.createElement("video"),
cover = window.content.document.createElement("div"),
canvas = window.content.document.createElement("canvas"),
photo = window.content.document.createElement("img"),
startbutton = window.content.document.createElement("button"),
width = 320,
height = 0;
photo.src = "http://placekitten.com/g/320/261"; window.content.document.body.insertBefore(video, window.content.document.body.firstChild);
var navigator = window.navigator;
navigator.getMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia(
{
video: true,
audio: false
},
function(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL.createObjectURL(stream);
}
video.play();
},
function(err) {
console.log("An error occured! " + err);
} );
video.addEventListener('canplay', function(ev){
if (!streaming) {
height = video.videoHeight / (video.videoWidth/width);
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
} }, false);
function takepicture() {
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data); }
startbutton.addEventListener('click', function(ev){
takepicture();
ev.preventDefault(); }, false); }
showCamera();
如果您的浏览器是 Firefox 并且仍然无法工作,请转到 about:config 并设置/添加一个名为 media.navigator.enabled 的布尔变量,其值为真
来源:https ://developer.mozilla.org/en-US/docs/WebRTC/Taking_webcam_photos
P/d:我在 Greasemonkey 脚本中使用了这段代码,它可以工作。我对原始代码的第一行做了一些更改。