Vue calls the computer camera to realize the photo function

Vue calls the computer camera to realize the photo function

This article example shares the specific code of vue to call the computer camera to realize the photo function for your reference. The specific content is as follows

Implementation effect diagram:

Before & After Taking Photos (My computer camera blocked the picture, so the picture is gray)

1. Click the photo upload function to retrieve the computer camera permissions

2. After selecting Allow to use the camera, the camera area on the page starts to display the image

3. Click the photo button and the captured picture will be displayed on the right. Click Save


Full code:

What I wrote here is a component, so the triggering event of calling the camera is passed from the parent component. You can also write directly on a page.

<template>
  <div class="camera-box" style="width: 900px;">
    <el-row :gutter="20">
      <el-col :span="12">
        <div style="text-align: center;font-size: 14px;font-weight: bold;margin-bottom: 10px;">Camera</div>
        <!-- This is the screen displayed by the camera-->
        <video id="video" width="400" height="300"></video>
        <div class="iCenter" >
          <el-button type='primary' size='small' icon="el-icon-camera" @click="takePhone" style="margin-top: 10px;">Take a photo</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div style="text-align: center;font-size: 14px;font-weight: bold;margin-bottom: 10px;">Photography effect</div>
        <!-- Here is the picture screen displayed when clicking to take a photo-->
        <canvas id='canvas' width='400' height='300' style="display: block;"></canvas>
        <el-button :loading="loadingbut" icon="el-icon-check" type='primary' size='small' @click="takePhoneUpfile" style="margin-top: 10px;">Save</el-button>
      </el-col>
    </el-row>
</div>
</template>
<script>
  import {putFileAttach} from "@/api/customer/animalinfo";
  export default {
    props:{
      tackPhoto:{//The state type passed from the parent component: Boolean,
        default:false
      }
    },
    data() {
      return {
        loadingbut:false,
        preViewVisible: false,
        blobFile: null,
        canvas: null,
        video: null,
        mediaStreamTrack: '',
      }
    },
    watch:{
      tackPhoto:{
        immediate: true,
        handler (newVal) {//After receiving the shooting status, start to retrieve the camera permissions. If the function is in a component, the following steps can be written directly in your own trigger method if (newVal) {
            var video = document.querySelector('video');
            var text = document.getElementById('text');
            // var mediaStreamTrack;
            
            // Compatible code window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
            
            if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
            }
            if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function(constraints) {
              var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
              if (!getUserMedia) {
              return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
              }
              return new Promise(function(resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
              });
            }
            } 
            
            //Camera call configuration var mediaOpts = {
            audio: false,
            video: true,
            video: { facingMode: "environment"} // or "user"
            // video: { width: 1280, height: 720 }
            // video: { facingMode: { exact: "environment" } } // or "user"
            }

            let that=this;
            navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
            that.mediaStreamTrack = stream;
            video = document.querySelector('video');
            if ("srcObject" in video) {
              video.srcObject = stream
            } else {
              video.src = window.URL && window.URL.createObjectURL(stream) || stream
            }
            video.play();
            }).catch(function (err) {
              console.log(err)
            });
          
        }
       },
        deep:true
      },
    },
    mounted() {
      // Camera this.video = document.getElementById('video');
      //Canvas this.canvas = document.getElementById('canvas')
      
    },
    methods: {
      takePhone() {//Click to take a photo let that = this;
        that.canvas.getContext('2d').drawImage(this.video, 0, 0, 400, 300);
        let dataurl = that.canvas.toDataURL('image/jpeg')
        that.blobFile = that.dataURLtoFile(dataurl, 'camera.jpg');
        that.preViewVisible = true
      },
      takePhoneUpfile() {//Save picture this.loadingbut=true;
        let formData = new FormData()
        formData.append('file', this.blobFile);//Picture content// Upload picture putFileAttach(formData).then(res=>{//Backend interface this.loadingbut=false;
          this.$emit('picture',res.data.data);
          this.tackPhoto=false;
          this.canvas.getContext('2d').clearRect(0, 0, 400, 300);//Clear canvas// Close the camera this.mediaStreamTrack.getVideoTracks().forEach(function (track) {
            track.stop();
           });
        },error=>{
          this.loadingbut=false;
          window.console.log(error);
        });
      },
    }
  }
</script>
<style>
 .camera-box #canvas{
  border: 1px solid #DCDFE6;
  }
</style>

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 implements calling PC camera to take photos in real time
  • Vue calls the PC 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

<<:  Example of converting timestamp to Date in MySQL

>>:  Detailed explanation of docker compose usage

Recommend

Write a publish-subscribe model with JS

Table of contents 1. Scene introduction 2 Code Op...

How to process local images dynamically loaded in Vue

Find the problem Today I encountered a problem of...

Use Vue3+Vant component to implement App search history function (sample code)

I am currently developing a new app project. This...

Diving into JS inheritance

Table of contents Preface Prepare Summarize n way...

A brief discussion on HTML table tags

Mainly discuss its structure and some important pr...

MySQL data types full analysis

Data Type: The basic rules that define what data ...

Understand the principles and applications of JSONP in one article

Table of contents What is JSONP JSONP Principle J...

Vue integrates PDF.js to implement PDF preview and add watermark steps

Table of contents Achieve results Available plugi...

MySQL column to row conversion and year-month grouping example

As shown below: SELECT count(DISTINCT(a.rect_id))...

Interviewers often ask questions about React's life cycle

React Lifecycle Two pictures to help you understa...

JS implements array filtering from simple to multi-condition filtering

Table of contents Single condition single data fi...

HTML+CSS to create heartbeat special effects

Today we are going to create a simple heartbeat e...

MySQL Series 12 Backup and Recovery

Table of contents Tutorial Series 1. Backup strat...

How to install WSL2 Ubuntu20.04 on Windows 10 and set up the docker environment

Enable WSL Make sure the system is Windows 10 200...