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

Vue implements click feedback instructions for water ripple effect

Table of contents Water wave effect Let's see...

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

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

Vue.js application performance optimization analysis + solution

Table of contents 1. Introduction 2. Why do we ne...

Detailed steps for installing MySQL using cluster rpm

Install MySQL database a) Download the MySQL sour...

Three methods to modify the hostname of Centos7

Method 1: hostnamectl modification Step 1 Check t...

Detailed tutorial on running multiple Springboot with Docker

Docker runs multiple Springboot First: Port mappi...

Example of how to implement underline effects using Css and JS

This article mainly describes two kinds of underl...

Flash embedded in web pages and IE, FF, Maxthon compatibility issues

After going through a lot of hardships, I searched...

Use of Linux watch command

1. Command Introduction The watch command execute...

Navicat for MySQL scheduled database backup and data recovery details

Database modification or deletion operations may ...

HTML adaptive table method

<body style="scroll:no"> <tabl...

Import CSS files using judgment conditions

Solution 1: Use conditional import in HTML docume...

How to configure MySQL master-slave replication under Windows

MySQL master-slave replication allows data from o...