Navigator.getUserMedia()方法提醒用户需要使用音频(0或者1)和(0或者1)视频输入设备,比如相机,屏幕共享,或者麦克风。如果用户给予许可,successCallback回调就会被调用,MediaStream
对象作为回调函数的参数。如果用户拒绝许可或者没有媒体可用,errorCallback就会被调用,类似的,PermissionDeniedError
或者NotFoundError
对象作为它的参数。注意,有可能以上两个回调函数都不被调用,因为不要求用户一定作出选择(允许或者拒绝)。
语法:
navigator.getUserMedia ( constraints, successCallback, errorCallback );
function(stream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(stream);
video.onloadedmetadata = function(e) {
// Do something with the video here.
};
}
参数
constraints
MediaStreamConstaints
对象指定了请求使用媒体的类型,还有每个类型的所需要的参数。具体细节请参见MediaDevices.getUserMedia()
方法下面的constraints部分。
在一个html页面调用js,首先完成compositionComplete,调用snapShot,采用Getusermedia,采集视频流,然后使用cavas画出一帧图像。并加水印保存到ICMS
示例代码:
//页面加载时必须完成一下动作,调用snapShot函数
this.compositionComplete = function () {
this.Visible.beginCameraDocVisible(true);
this.Visible.waitingCameraDocVisible(false);
this.Visible.endCameraDocVisible(false);
setTimeout(self.snapShot, 50);
};
//页面一打开,便调出摄像头,getUserMedia,采集视频流
this.snapShot = function () {
self.video.loop = self.video.muted = true;
self.video.load();
var constraints = {
//audio: true,
video: {
facingMode: "environment",
width: 800,
height: 800
}
};
navigator.mediaDevices.getUserMedia(constraints)
.then(function (stream) {
self.mediaStream = stream;
console.info("after mediaStream");
var deferred = $.Deferred();
self.video.oncanplay = function (e) {
console.info("after oncanplay");
setTimeout(function () {
self.video.play();
self.canvas.width = self.video.videoWidth;
self.canvas.height = self.video.videoHeight;
}, 500);
setTimeout(function () { deferred.resolve(e); }, 2000);
};
console.info("before window.URL.createObjectURL");
self.video.src = window.URL.createObjectURL(stream);
console.info("after window.URL.createObjectURL");
return deferred.promise();
})
.then(function (e) {
//return self.TakePhoto();
})
.then(function () {
//self.SelectPhoto();
})
.catch(function (e) {
self.stop();
self.FailToAccessCamera();
})
;
};
//开始拍照,使用drawImage画布画图,并用fillText把水印加上,此时相机不可用,画布可用
this.TakePhoto = function () {
var context = self.canvas.getContext('2d');
context.drawImage(self.video, 0, 0, self.canvas.width, self.canvas.height);
//
context.font = "italic 20px sans-serif";
context.fillText("*****", 0, self.canvas.height - 10);
context.fillText(new Date().Format("yyyy-MM-dd HH:mm:ss"), 0, self.canvas.height - 30);
self.Visible.video(false);
self.Visible.canvas(true);
};