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 tutorial on installation and configuration of MySql 5.7.17 winx64

1. Download the software 1. Go to the MySQL offic...

Why does your height:100% not work?

Why doesn't your height:100% work? This knowl...

How to display percentage and the first few percent in MySQL

Table of contents Require Implementation Code dat...

Learn how to write neat and standard HTML tags

Good HTML code is the foundation of a beautiful w...

Steps to install RocketMQ instance on Linux

1. Install JDK 1.1 Check whether the current virt...

Graphical explanation of the solutions for front-end processing of small icons

Preface Before starting this article, let’s do a ...

Summary of JavaScript JSON.stringify() usage

Table of contents 1. Usage 1. Basic usage 2. The ...

How to manually upgrade the node version under CentOs

1. Find the corresponding nodejs package, refer t...

How to add sudo permissions to a user in Linux environment

sudo configuration file The default configuration...

How to migrate mysql storage location to a new disk

1. Prepare a new disk and format it with the same...

Detailed explanation of the knowledge points of using TEXT/BLOB types in MySQL

1. The difference between TEXT and BLOB The only ...

Implementation of deploying war package project using Docker

To deploy war with Docker, you must use a contain...