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

vue實現(xiàn)拍照或錄像的示例代碼

 更新時間:2023年11月06日 16:54:45   作者:無妄的罪  
這篇文章主要為大家詳細(xì)介紹了如何利用vue實現(xiàn)拍照或錄像的功能,文中的示例代碼講解詳細(xì),具有一定的參考價值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

這是一個涉及到Vue和原生相機(jī)API的復(fù)雜問題。首先,我要指出的是,這個功能需要使用到一些特定的插件或者原生代碼來實現(xiàn),因為Webview默認(rèn)并不提供直接訪問手機(jī)攝像頭的權(quán)限。因此,如果你正在創(chuàng)建一個用于發(fā)布到Web的應(yīng)用,那么你可能需要找到一種在瀏覽器中實現(xiàn)這個功能的其他方式。然而,如果你正在創(chuàng)建一個原生應(yīng)用(比如一個使用Vue.js的Android或iOS應(yīng)用),那么你可以直接使用相應(yīng)的API來訪問攝像頭。

對于Vue部分,你可以創(chuàng)建一個組件,包含一個<video>元素用來展示攝像頭的內(nèi)容,以及一個按鈕用來觸發(fā)拍照或錄像。下面是一個基礎(chǔ)的示例:

<template>
<div>
<video ref="videoElement" width="640" height="480" autoplay></video>
<button @click="takePhotoOrVideo">拍照/錄像</button>
<div v-for="(clip, index) in clips" :key="index">
<video :src="clip" controls></video>
</div>
</div>
</template>
 
<script>
export default {
data() {
return {
clips: [],
clipIndex: 0,
isRecording: false,
photoOrVideoTime: 0,
};
},
methods: {
takePhotoOrVideo() {
if (this.isRecording) {
this.clipIndex++;
if (this.clipIndex >= this.clips.length) {
this.clipIndex = 0;
}
this.isRecording = false;
} else {
this.startRecording();
}
},
startRecording() {
this.clips.push(URL.createObjectURL(this.$refs.videoElement.captureStream(20))); // 每20秒一個片段
this.clipIndex++;
this.isRecording = true;
this.photoOrVideoTime = 0;
},
},
};
</script>

這個Vue組件首先創(chuàng)建了一個<video>元素用來展示攝像頭的內(nèi)容,以及一個按鈕用來觸發(fā)拍照或錄像。在takePhotoOrVideo方法中,如果正在錄像,就會播放剛才錄制的視頻;否則,開始錄像。在startRecording方法中,使用captureStream方法來開始錄像,并把錄像轉(zhuǎn)換為URL以便播放。這個方法每20秒就會創(chuàng)建一個新的錄像片段。請注意,這個方法只能在支持captureStream方法的瀏覽器中使用。如果你需要在不支持這個方法的瀏覽器中使用攝像頭,你可能需要使用一些第三方的解決方案,比如WebRTC。

方法補充

除了上文的方法,小編還為大家整理了其他Vue實現(xiàn)拍照功能的示例代碼,希望對大家有所幫助

方法一:vue實現(xiàn)調(diào)用攝像頭和拍照功能

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'
Vue.use(ElementUI)
new Vue({
  el: '#app',
  render: h => h(App)
})
<template>
  <div class="camera_outer">
    <video
      id="videoCamera"
      :width="videoWidth"
      :height="videoHeight"
      autoplay
    ></video>
    <canvas
      style="display: none"
      id="canvasCamera"
      :width="videoWidth"
      :height="videoHeight"
    ></canvas>
    <div v-if="imgSrc" class="img_bg_camera">
      <p>效果預(yù)覽</p>
      <img :src="imgSrc" alt class="tx_img" />
    </div>
    <div class="button">
      <el-button @click="getCompetence()" type="primary">打開攝像頭</el-button>
      <el-button @click="stopNavigator()" type="warning">關(guān)閉攝像頭</el-button>
      <el-button @click="setImage()" type="success">拍照</el-button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      videoWidth: 250,
      videoHeight: 350,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      openVideo: false,
    };
  },
  mounted() {
    this.getCompetence(); //進(jìn)入頁面就調(diào)用攝像頭
  },
  methods: {
    // 調(diào)用權(quán)限(打開攝像頭功能)
    getCompetence() {
      var _this = this;
      _this.thisCancas = document.getElementById("canvasCamera");
      _this.thisContext = this.thisCancas.getContext("2d");
      _this.thisVideo = document.getElementById("videoCamera");
      _this.thisVideo.style.display = "block";
      // 獲取媒體屬性,舊版本瀏覽器可能不支持mediaDevices,我們首先設(shè)置一個空對象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些瀏覽器實現(xiàn)了部分mediaDevices,我們不能只分配一個對象
      // 使用getUserMedia,因為它會覆蓋現(xiàn)有的屬性。
      // 這里,如果缺少getUserMedia屬性,就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先獲取現(xiàn)存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些瀏覽器不支持,會返回錯誤信息
          // 保持接口一致
          if (!getUserMedia) {
            //不存在則報錯
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否則,使用Promise將調(diào)用包裝到舊的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 舊的瀏覽器可能沒有srcObject
          if ("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) => {
          console.log(err);
        });
    },
    //  繪制圖片(拍照功能)
    setImage() {
      var _this = this;
      // canvas畫圖
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      );
      // 獲取圖片base64鏈接
      var image = this.thisCancas.toDataURL("image/png");
      _this.imgSrc = image; //賦值并預(yù)覽圖片
    },
    // 關(guān)閉攝像頭
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
    },
    // base64轉(zhuǎn)文件,此處沒用到
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
  },
};
</script>
<style scoped>
</style>

方法二:vue調(diào)用電腦端攝像頭實時拍照

html模塊

//點擊打開照相機(jī)拍照彈窗
<el-button @click="handleOpen">照相機(jī)拍照</el-button>

//照相機(jī)拍照彈窗
    <div class="public-mask mask-grey-bg" v-show="cameraOpen">
      <div class="mask-main camera-main">
        <div class="mask-title">
          <img src="../assets/images/icon_camera.png" class="title-icon"/>
          <span>照相機(jī)拍照</span>
          <img src="../assets/images/icon_close.png" class="title-close" @click="closeCameraMask"/>
        </div>
        <div class="camera-box">
          <div class="camera-left">
            <!-- 這里就是攝像頭顯示的畫面 -->
            <video id="videoCamera" width="100%" height="100%"></video>
          </div>
          <div class="camera-right">
        
            <div class="camera-img-box">
              <div class="small-img">
               <!-- 這里是點擊拍照顯示的圖片畫面 -->
                <img v-if="imgSrc" :src="imgSrc" style="width: 200px;height: 150px;" />
                <canvas id="canvasCamera" class="canvas" :width='videoWidth' :height='videoHeight' style="display: none;"></canvas>
              </div>
              <div>
              <!-- 點擊拍照和保存按鈕 -->
                <el-button type="primary" class="save-camera-btn" icon="el-icon-camera" @click="drawImage" style="margin-top: 10px;">拍照</el-button>
                <el-button type="primary" class="save-camera-btn" icon="el-icon-check" @click="uploadPicture">保存</el-button>
              </div>
            </div>
            
          </div>
          
        </div>
      </div>
    </div>

js模塊

export default {
  name: "Index",
  data() {
  	return {
  	  /** 照相機(jī)彈窗模塊-start */
      cameraOpen: false,
      imgSrc: undefined,
      os: false,//控制攝像頭開關(guān)
      thisVideo: null,
      thisContext: null,
      thisCancas: null,
      videoWidth: 800,
      videoHeight: 600,
      /** 照相機(jī)彈窗模塊-end */
  	}
  },
  methods: {
  /** 調(diào)用攝像頭拍照-start*/
  	// 打開照相機(jī)彈窗
  	handleOpen() {
  	  this.cameraOpen = true;
      this.getCompetence();
  	},
    // 調(diào)用攝像頭權(quán)限
    getCompetence() {
      //必須在model中render后才可獲取到dom節(jié)點,直接獲取無法獲取到model中的dom節(jié)點
      this.$nextTick(() => {
        const _this = this;
        this.os = false;//切換成關(guān)閉攝像頭
        this.thisCancas = document.getElementById('canvasCamera');//這里是需要截取的canvas的Id名稱
        this.thisContext = this.thisCancas.getContext('2d');
        this.thisVideo = document.getElementById('videoCamera');
        // 舊版本瀏覽器可能根本不支持mediaDevices,我們首先設(shè)置一個空對象
        if (navigator.mediaDevices === undefined) {
          navigator.menavigatordiaDevices = {}
        }
        // 一些瀏覽器實現(xiàn)了部分mediaDevices,我們不能只分配一個對象
        // 使用getUserMedia,因為它會覆蓋現(xiàn)有的屬性。
        // 這里,如果缺少getUserMedia屬性,就添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先獲取現(xiàn)存的getUserMedia(如果存在)
            let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
            // 有些瀏覽器不支持,會返回錯誤信息
            // 保持接口一致
            if (!getUserMedia) {
              return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
            }
            // 否則,使用Promise將調(diào)用包裝到舊的navigator.getUserMedia
            return 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) {
          // 舊的瀏覽器可能沒有srcObject
          if ('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.$notify({
            title: '警告',
            message: '沒有開啟攝像頭權(quán)限或瀏覽器版本不兼容.',
            type: 'warning'
          });
        });
      });
    },
    //繪制圖片
    drawImage() {
      // 點擊,canvas畫圖
      this.thisContext.drawImage(this.thisVideo, 0, 0, this.videoWidth, this.videoHeight);
      // 獲取圖片base64鏈接,展示到界面中的也是這個url地址
      this.imgSrc = this.thisCancas.toDataURL('image/png');
    },
    // 上傳照相機(jī)圖片
    uploadPicture() {
      // 這里就調(diào)用上傳圖片接口即可
      ...
    },
    //清空畫布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    //重置畫布
    resetCanvas() {
      this.imgSrc = "";
      this.clearCanvas('canvasCamera');
    },
    //關(guān)閉攝像頭
    stopNavigator() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true;//切換成打開攝像頭
      }
    },
    // 關(guān)閉照相機(jī)彈窗
    closeCameraMask() {
      this.cameraOpen = false; // 關(guān)閉照相機(jī)彈窗
      this.resetCanvas(); // 重置畫布
      this.stopNavigator(); // 關(guān)閉攝像頭
      //this.getDetailList(); // 重新獲取一下List,此方法不再書寫
    },
    /** 調(diào)用攝像頭拍照-end*/
  },
}

到此這篇關(guān)于vue實現(xiàn)拍照或錄像的示例代碼的文章就介紹到這了,更多相關(guān)vue拍照錄像內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue搭建簡易前端的思路及問題詳解

    vue搭建簡易前端的思路及問題詳解

    這篇文章主要介紹了如何使用Vue和ElementPlus構(gòu)建前端頁面,特別是如何進(jìn)行跨域請求和使用Vue?Router進(jìn)行路由管理,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-01-01
  • vue實現(xiàn)彈幕功能

    vue實現(xiàn)彈幕功能

    這篇文章主要介紹了vue實現(xiàn)彈幕功能,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-10-10
  • petite?vue的使用示例詳解

    petite?vue的使用示例詳解

    這篇文章主要為大家介紹了petite?vue的使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • 使用vue-router與v-if實現(xiàn)tab切換遇到的問題及解決方法

    使用vue-router與v-if實現(xiàn)tab切換遇到的問題及解決方法

    這篇文章主要介紹了vue-router與v-if實現(xiàn)tab切換的思考,需要的朋友可以參考下
    2018-09-09
  • vue quill editor 使用富文本添加上傳音頻功能

    vue quill editor 使用富文本添加上傳音頻功能

    vue-quill-editor 是vue項目中常用的富文本插件,其功能能滿足大部分的項目需求。這篇文章主要介紹了vue-quill-editor 富文本添加上傳音頻功能,需要的朋友可以參考下
    2020-01-01
  • 解決el-tree節(jié)點過濾不顯示下級的問題

    解決el-tree節(jié)點過濾不顯示下級的問題

    這篇文章主要介紹了解決el-tree節(jié)點過濾不顯示下級的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • ant-design-vue中設(shè)置Table每頁顯示的條目數(shù)量方式

    ant-design-vue中設(shè)置Table每頁顯示的條目數(shù)量方式

    這篇文章主要介紹了ant-design-vue中設(shè)置Table每頁顯示的條目數(shù)量方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • vue環(huán)境搭建簡單教程

    vue環(huán)境搭建簡單教程

    這篇文章主要介紹了vue環(huán)境搭建簡單教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • vue+SpringBoot使用WebSocket方式

    vue+SpringBoot使用WebSocket方式

    WebSocket是一種全雙工通信協(xié)議,通過HTTP升級機(jī)制建立連接,支持實時雙向數(shù)據(jù)傳輸,示例代碼展示了如何在Java Spring Boot和Vue.js中實現(xiàn)WebSocket服務(wù)和客戶端
    2025-02-02
  • vue中自定義組件雙向綁定的三種方法總結(jié)

    vue中自定義組件雙向綁定的三種方法總結(jié)

    這篇文章主要介紹了vue中自定義組件雙向綁定的三種方法總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06

最新評論