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

Detailed explanation of the method of comparing dates in MySQL

If there is a table product with a field add_time...

Setting up VMware vSphere in VMware Workstation (Graphic Tutorial)

VMware vSphere is the industry's leading and ...

MySQL 5.6.36 Windows x64 version installation tutorial detailed

1. Target environment Windows 7 64-bit 2. Materia...

Web designers also need to learn web coding

Often, after a web design is completed, the desig...

A brief analysis of MySQL's lru linked list

1. Briefly describe the traditional LRU linked li...

Detailed explanation of how to use $props, $attrs and $listeners in Vue

Table of contents background 1. Document Descript...

Linux Centos8 Create CA Certificate Tutorial

Install Required Files Yum install openssl-* -y C...

Advanced and summary of commonly used sql statements in MySQL database

This article uses examples to describe the common...

VMware15 installation of Deepin detailed tutorial (picture and text)

Preface When using the Deepin user interface, it ...

Detailed explanation of SQL injection - security (Part 2)

If there are any errors in this article or you ha...

In-depth explanation of binlog in MySQL 8.0

1 Introduction Binary log records SQL statements ...

Installation, activation and configuration of ModSecurity under Apache

ModSecurity is a powerful packet filtering tool t...

Several ways to implement "text overflow truncation and omission" with pure CSS

In our daily development work, text overflow, tru...