Vue implements calling PC camera to take photos in real time

Vue implements calling PC camera to take photos in real time

Vue calls the PC camera to take pictures in real time, for your reference, the specific content is as follows

Since I use the click button to open the modal box to take a photo, paste the button and modal box codes here as follows.

<!-- Open modal box button-->
        <el-form-item label="*Photo:" prop="headImage">
          <el-input type="text" v-model="imgSrc" />
            <el-col :span="1.5">
              <el-button
                @click="onTake"
                icon="el-icon-camera"
                size="small">
                Take a photo and upload it</el-button>
            </el-col>
        </el-form-item>
        <!--Show the picture after taking the photo-->
        <el-form-item label="" prop="imgSrc">
          <img v-if="imgSrc" :src="imgSrc" style="width: 200px;height: 240px;" />
</el-form-item> 

<!--Photographing modal box-->
    <el-dialog
      title="Photo upload"
      :visible.sync="visible"
      @close="onCancel"
      width="1065px">
      <div class="box">
        <video id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight" autoPlay></video>
        <canvas id="canvasCamera" class="canvas" :width="videoWidth" :height="videoHeight"></canvas>
      </div>
      <div slot="footer">
        <el-button
          @click="drawImage"
          icon="el-icon-camera"
          size="small">
          Take a photo</el-button>
        <el-button
          v-if="os"
          @click="getCompetence"
          icon="el-icon-video-camera"
          size="small">
          Open camera</el-button>
        <el-button
          v-else
          @click="stopNavigator"
          icon="el-icon-switch-button"
          size="small">
          Close camera</el-button>
        <el-button
          @click="resetCanvas"
          icon="el-icon-refresh"
          size="small">
          Reset</el-button>
        <el-button
          @click="onCancel"
          icon="el-icon-circle-close"
          size="small">
          Done</el-button>
   </div>
</el-dialog>

Next, let's look at the js code. I deleted the unnecessary parts because it involves unit project issues. I'm really sorry.

<script>
export default {
  name: "XXX",
  data() {
    return {
      visible: false, //Popup loading: false, //Upload button loading os: false, //Control camera switch thisVideo: null,
      thisContext: null,
      thisCancas: null,
      videoWidth: 500,
      videoHeight: 400,
      postOptions:[],
      CertCtl:'',
      // Mask layer loading: true,
      // Select array ids: [],
      // Non-single disable single: true,
      // Non-multiple disable multiple: true,
      //Total number of entries: 0,
      // Project personnel table data akworkerList: [],
      //Worker Type Data Dictionary workerTypeOptions:[],
      // Popup layer title: "",
      // Whether to display the pop-up layer open: false,
      // Query parameters queryParams: {
        pageNum: 1,
        pageSize: 10,
        imgSrc:undefined,
      },
      // Form parameters form: {},
      // Form validation rules: {
      }
    };
  },
  created() {
   
  },
  methods: {
    /*Call the camera to start taking pictures*/
    onTake() {
      this.visible = true;
      this.getCompetence();
    },
    onCancel() {
      this.visible = false;
     /* this.resetCanvas();*/
      this.stopNavigator();
    },
    //Call camera permission getCompetence() {
      //The DOM node can only be obtained after rendering in the model. Directly obtaining the DOM node in the model cannot be obtained this.$nextTick(() => {
        const _this = this;
        this.os = false; //Switch to close the camera this.thisCancas = document.getElementById('canvasCamera');
        this.thisContext = this.thisCancas.getContext('2d');
        this.thisVideo = document.getElementById('videoCamera');
        // Older browsers may not support mediaDevices at all, so we first set an empty object if (navigator.mediaDevices === undefined) {
          navigator.menavigatordiaDevices = {}
        }
        // Some browsers implement partial mediaDevices, and we can't just assign an object // using getUserMedia because it will overwrite existing properties.
        // Here, if the getUserMedia property is missing, add it.
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            // First get the existing getUserMedia (if it exists)
            let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
            // Some browsers do not support it and will return an error message // Keep the interface consistent if (!getUserMedia) {
              return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
            }
            // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
            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) {
          // Old browsers may not have srcObject
          if ('srcObject' in _this.thisVideo) {
            _this.thisVideo.srcObject = stream
          } else {
            // Avoid using this in newer browsers as it is being deprecated.
            _this.thisVideo.src = window.URL.createObjectURL(stream)
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play()
          }
        }).catch(err => {
          this.$notify({
            title: 'Warning',
            message: 'The camera permission is not enabled or the browser version is incompatible.',
            type: 'warning'
          });
        });
      });
    },
    //Draw the image drawImage() {
      // Click, canvas drawing this.thisContext.drawImage(this.thisVideo, 0, 0, this.videoWidth, this.videoHeight);
      // Get the base64 link of the image this.imgSrc = this.thisCancas.toDataURL('image/png');
      /*const imgSrc=this.imgSrc;*/
    },
    // Clear the canvas clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    //Reset the canvas resetCanvas() {
      this.imgSrc = "";
      this.clearCanvas('canvasCamera');
    },
    //Close the camera stopNavigator() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true; //Switch to open the camera}
    },
  /*Call the camera to take pictures*/
  }
};
</script>

Here, this article has been shared. If there is anything wrong, I hope you can give me more advice. If there are similarities, please contact me to modify and delete them. Thank you

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue calls the PC camera to realize the photo function
  • Vue calls the computer camera to realize the photo function
  • Vue calls the local camera to realize the photo function
  • Vue2.0 implements the function of calling the camera to take pictures, and exif.js implements the picture upload function
  • Vue calls the camera to take pictures and save them locally

<<:  Docker automated build Automated Build implementation process diagram

>>:  Detailed explanation of the difference between MySQL null and not null and null and empty value ''''

Recommend

Tutorial on deploying jdk and tomcat on centos7 without interface

1. Install xshell6 2. Create a server connection ...

Troubleshooting the cause of 502 bad gateway error on nginx server

The server reports an error 502 when synchronizin...

Solve the problem of Syn Flooding in MySQL database

Syn attack is the most common and most easily exp...

How to block IP and IP range in Nginx

Written in front Nginx is not just a reverse prox...

Linux RabbitMQ cluster construction process diagram

1. Overall steps At the beginning, we introduced ...

How to smoothly go online after MySQL table partitioning

Table of contents Purpose of the table For exampl...

Zookeeper stand-alone environment and cluster environment construction

1. Single machine environment construction# 1.1 D...

Vue dynamic menu, dynamic route loading and refresh pitfalls

Table of contents need: Ideas: lesson: Share the ...

Three ways to avoid duplicate insertion of data in MySql

Preface In the case of primary key conflict or un...

How to quickly copy large files under Linux

Copy data When copying data remotely, we usually ...

HTML table tag tutorial (35): cross-column attribute COLSPAN

In a complex table structure, some cells span mul...

Docker practice: Python application containerization

1. Introduction Containers use a sandbox mechanis...

Tutorial analysis of quick installation of mysql5.7 based on centos7

one. wget https://dev.mysql.com/get/mysql57-commu...