VUE调用pc端摄像头
生活随笔
收集整理的這篇文章主要介紹了
VUE调用pc端摄像头
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
VUE項目調用pc端攝像頭功能
(攝像頭只可以用localhost啟用項目訪問,或者修改瀏覽器配置,底部有方法)
代碼如下:
js
<script>export default {name: "camera",data() {return {os: false,//控制攝像頭開關thisVideo: null,thisContext: null,thisCancas: null,imgSrc: '',videoWidth: 500,videoHeight: 400,};},created() {this.openCamera();},methods: {submitBtn() {console.log(this.imgSrc);},// 調用攝像頭權限openCamera() {//必須在model中render后才可獲取到dom節點,直接獲取無法獲取到model中的dom節點this.$nextTick(() => {const _this = this;this.os = false;//切換成關閉攝像頭this.thisCancas = document.getElementById('canvasCamera');this.thisContext = this.thisCancas.getContext('2d');this.thisVideo = document.getElementById('videoCamera');// 舊版本瀏覽器可能根本不支持mediaDevices,我們首先設置一個空對象if (navigator.mediaDevices === undefined) {navigator.mediaDevices= {}}// 一些瀏覽器實現了部分mediaDevices,我們不能只分配一個對象// 使用getUserMedia,因為它會覆蓋現有的屬性。// 這里,如果缺少getUserMedia屬性,就添加它。if (navigator.mediaDevices.getUserMedia === undefined) {navigator.mediaDevices.getUserMedia = function (constraints) {// 首先獲取現存的getUserMedia(如果存在)let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;// 有些瀏覽器不支持,會返回錯誤信息// 保持接口一致if (!getUserMedia) {return Promise.reject(new Error('getUserMedia is not implemented in this browser'))}// 否則,使用Promise將調用包裝到舊的navigator.getUserMediareturn new Promise(function (resolve, reject) {getUserMedia.call(navigator, constraints, resolve, reject)})}}const constraints = {audio: false,video: {width: _this.videoWidth, height: _this.videoHeight, transform: 'scaleX(-1)'}};navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {// 舊的瀏覽器可能沒有srcObjectif ('srcObject' in _this.thisVideo) {_this.thisVideo.srcObject = stream} else {// 避免在新的瀏覽器中使用它,因為它正在被棄用。_this.thisVideo.src = window.URL.createObjectURL(stream)}_this.thisVideo.onloadedmetadata = function (e) {_this.thisVideo.play()}}).catch(err => {this.$message({message: '沒有開啟攝像頭權限或瀏覽器版本不兼容',type: 'warning'});});});},//拍照按鈕photographBtn() {// 點擊,canvas畫圖this.thisContext.drawImage(this.thisVideo, 0, 0, this.videoWidth, this.videoHeight);// 獲取圖片base64鏈接this.imgSrc = this.thisCancas.toDataURL('image/png');},//清空畫布clearCanvas(id) {let c = document.getElementById(id);let cxt = c.getContext("2d");cxt.clearRect(0, 0, c.width, c.height);},//重置畫布resetBtn() {this.imgSrc = "";this.clearCanvas('canvasCamera');},//關閉攝像頭stopCamera() {if (this.thisVideo && this.thisVideo !== null) {this.thisVideo.srcObject.getTracks()[0].stop();this.os = true;//切換成打開攝像頭}},}}; </script>另外還有一篇解決攝像頭用IP訪問的解決方法原文鏈接如下
chrome只支持https\ 127.0.0.1\localhost三種地址方式調用攝像頭,http方式不支持直接調用
總結
以上是生活随笔為你收集整理的VUE调用pc端摄像头的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS7 初次安装记录(一)安装完
- 下一篇: imacros自动跑代码_如何使用iMa