欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript實(shí)現(xiàn)拍照功能詳細(xì)示例代碼

 更新時(shí)間:2023年07月27日 11:12:03   作者:街尾雜貨店&  
這篇文章主要給大家介紹了關(guān)于javascript實(shí)現(xiàn)拍照功能的相關(guān)資料, 最近做項(xiàng)目,遇到一個(gè)正常但又少見(jiàn)的需求之拍照,文中給出了詳細(xì)的代碼示例,需要的朋友可以參考下

介紹

HTML5 的 getUserMedia API 為用戶(hù)提供訪(fǎng)問(wèn)硬件設(shè)備媒體(攝像頭、視頻、音頻、地理位置等)的接口,基于該接口,開(kāi)發(fā)者可以在不依賴(lài)任何瀏覽器插件的條件下訪(fǎng)問(wèn)硬件媒體設(shè)備。

另外,主流瀏覽器 Firefox、Chrome、Safari、Opera 等等已經(jīng)全面支持。

一、獲取視頻流,并用 video 標(biāo)簽播放

 <video id="video" autoplay></video>
const videoConstraints = { width: 1366, height: 768 };
const videoNode = document.querySelector('#video');
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints });
videoNode.srcObject = stream;
videoNode.play();

二、多個(gè)攝像頭設(shè)備切換

// enumerateDevices獲取所有媒體設(shè)備
const mediaDevices = await navigator.mediaDevices.enumerateDevices();

// 通過(guò)設(shè)備實(shí)例king屬性videoinput,過(guò)濾獲取攝像頭設(shè)備
const videoDevices = mediaDevices.filter(item => item.kind === 'videoinput') || [];

// 獲取前置攝像頭
const videoDeviceId = videoDevices[0].deviceId;
const videoConstraints = { deviceId: { exact: videoDeviceId }, width: 1366, height: 768 };
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints });

// 獲取后置攝像頭
const videoDeviceId = videoDevices[1].deviceId;
const videoConstraints = { deviceId: { exact: videoDeviceId }, width: 1366, height: 768 };
let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints });

// 依次類(lèi)推...

三、拍照保存圖片

// 通過(guò)canvas捕捉video流,生成base64格式圖片
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = 1366;
canvas.height = 768;
context.drawImage(videoNode, 0, 0, canvas.width, canvas.height);
download(canvas.toDataURL('image/jpeg'));

// 下載圖片
function download (src) {
   if (!src) return;
   const a = document.createElement('a');
   a.setAttribute('download', new Date());
   a.href = src;
   a.click();
}

關(guān)閉攝像頭設(shè)備

let stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: videoConstraints });
// 3s后關(guān)閉攝像頭
setTimeout(function () {
    stream.getTracks().forEach(track => track.stop());
    stream = null;
}, 3000);

總結(jié) 

到此這篇關(guān)于javascript實(shí)現(xiàn)拍照功能的文章就介紹到這了,更多相關(guān)javascript拍照功能實(shí)現(xiàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論