首页 前端知识 vue生成二维码与识别,vue扫一扫功能实现

vue生成二维码与识别,vue扫一扫功能实现

2024-06-20 09:06:43 前端知识 前端哥 110 765 我要收藏

一 、安装qrcode

npm install qrcode

二、生成二维码

<!--    html部分  -->
<template>
        <div class="all">
          <div class="qr_center">
            <canvas id="canvass"></canvas>
          </div>
        </div>
</template>

<script>
   useqrcode(createId) {
      // createId是生成的二维码内容,可以添加变量或字符串随自己心意
      // this.$nextTick()  异步执行dom更新,一旦观察到数据变化就会开启一个队列,
      // 我是这个地方,是运用在一个vue项目里编写的 html部分写在了一个弹窗里面,所以使用
      //了this.$nextTick来获取 document.getElementById('canvass')
      this.coding = true;
      this.$nextTick(() =>{
        let canvas = document.getElementById('canvass')
        QRCode.toCanvas(canvas, createId, error=>{
          if (error) console.error(error)
        })
      })
    },
</script>

三、html部分,上传二维码解析(数据库或图片服务器未做存储的情况下,将你生成的 二维码保存本地上传),另外提醒一下使用$函数要下载或引用Jquery

<template>
	<div>
		<div>
			<input style="text-align: center" type='text' id='file' disabled="disabled" class="form-control" />&nbsp;
				<span class="input-group-btn"><button id="btn" type='button' class='btn btn-primary language_label'
				@click="analysis" onclick="document.getElementById('pictureChange').click()">选择文件</button>
				</span>
				<input  type="file" id="pictureChange" class="file2" style="display: none" onchange="document.getElementById('file').value=this.value.substring(this.value.lastIndexOf('\\')+1)" />
		</div>

		<div>
			<h4>识别结果:</h4>
			<ul id="result"></ul>
			<div id="bos"></div>
		</div>
	</div>
</template>
<script>
    analysis(){
      let cd = [];
      this.$nextTick(() =>{
        $("#bos").append('<canvas id="qrcanvas" style="display:none;"></canvas>')
        $("#pictureChange").change(function (e) {
          let file = e.target.files[0];
          if(window.FileReader) {
            let fr = new FileReader();
            fr.readAsDataURL(file);
            fr.onloadend = function(e) {
              let base64Data = e.target.result;
              base64ToqR(base64Data)
            }
          }
        })

        function base64ToqR(data) {
          var c = document.getElementById("qrcanvas");
          var ctx = c.getContext("2d");

          var img = new Image();
          img.src = data;
          img.onload = function() {
            $("#qrcanvas").attr("width",img.width)
            $("#qrcanvas").attr("height",img.height)
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var imageData = ctx.getImageData(0, 0, img.width, img.height);
            const code = jsQR(imageData.data, imageData.width, imageData.height, {
              inversionAttempts: "dontInvert",
            });
            if(code){
              Encode.push(code.data)
              showCode(code.data)
              return
            }else{
              alert("识别错误")
            }
          };
        }

        function showCode(code){
          $("#result").append("<li>"+code+"</li>")
        }
      })
    },
</script>

以下是移动端的扫一扫解析方法

一,安装jsQR

 npm install jsqr --save

二、扫一扫使用

<template>
  <div  class="scan">
    <div class="video-container">
      <video class="video" id="video-1"></video>
    </div>
    <div class="camera-container" v-if="videoInputDevices.length">
      <label>摄像头:</label>
      <select v-model="currentVideoInputDevice">
        <option
          v-for="(videoInputDevice, index) in videoInputDevices"
          :key="index"
          :value="videoInputDevice"
        >
          {{ videoInputDevice.label }}
        </option>
      </select>
    </div>
  </div>
</template>



<script >
import {
  BrowserMultiFormatReader,
  ChecksumException,
  FormatException,
} from "@zxing/library";
export default {
  data() {
    return {
      codeReader: new BrowserMultiFormatReader(),
      videoInputDevices: [],
      currentVideoInputDevice: {},
      decodeResult: undefined,
    };
  },
  created() {},
    methods: {
    async openScan() {
      const _this = this;
      _this.codeReader
        .getVideoInputDevices() //老版本listVideoInputDevices()
        .then((videoInputDevices) => {
          if (videoInputDevices && videoInputDevices.length) {
            if (videoInputDevices.length > 1) {
              videoInputDevices.reverse();
            } //防止先唤出前摄像头
            _this.videoInputDevices = videoInputDevices;
            _this.currentVideoInputDevice = videoInputDevices[0];
          }
        })
        .catch(() => {});
    },

    decodeFromInputVideo() {
      const _this = this;
      _this.codeReader.reset();
      // 多次
      _this.codeReader.decodeFromVideoDevice(
        _this.currentVideoInputDevice.deviceId,
        "video-1",
        (result, err) => {
          if (result) {
            _this.decodeResult = result;
          }
          if (err) {
            if (err instanceof ChecksumException) {
              console.log(
                "A code was found, but it's read value was not valid."
              );
            }
            if (err instanceof FormatException) {
              console.log("A code was found, but it was in a invalid format.");
            }
          }
        }
      );
    },

    successDecode() {
      const _this = this;
     
      alert(_this.decodeResult.text)
      alert("Hi! Welcome to my world!")
    },
  },
  watch: {
    currentVideoInputDevice: function () {
      this.decodeFromInputVideo();
    },
    decodeResult: function () {
      this.successDecode();
    },
  },
  mounted: function () {
    this.openScan();
  },
  unmounted: function () {
    this.codeReader.reset(); //关闭
  },
};
</script>

<style scoped lang="scss">
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.scan {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #ff9900;
  width: 100vw;
  height: 100vh;
  background: #000;
  .video-container {
    margin-top: 10px;
    display: flex;
    justify-content: center;
    video {
      width: 96vw;
      max-height: 80vh;
    }
    @media (min-width: 500px) {
      video {
        // width: 80vh;
        max-width: 96vw;
        height: 80vh;
      }
    }
  }
  .camera-container {
    margin-top: 5vh;
    width: 80%;
    height: 50px;
    line-height: 44px;
    border-radius: 10px;
    border: 3px solid #ff9900;
    display: flex;
    justify-content: center;
    select {
      width: calc(100% - 80px);
      color: #ff9900;
      background: transparent;
      border: none;
      outline: none;
    }
  }
}
</style>

在这里插入图片描述

这是直接字符串生成二维码的代码或许能给你一些灵感,copy 直接运行即可

<template>
  <div class="all">
    <div class="ip-app">
      <!--页头-->
      <el-breadcrumb separator-class="el-icon-arrow-right" class="ip-head">
        <el-breadcrumb-item>资产管理</el-breadcrumb-item>
        <el-breadcrumb-item>二维码生成</el-breadcrumb-item>
      </el-breadcrumb>
    <div class="QR_switchover">
      <span>二维码生成</span>
    </div>
    <div class="QRCode_seek">
      <div>请输入内容:</div>
      <div><el-input v-model="txt"></el-input></div>
      <div><el-button @click="create()" type="primary">生成</el-button></div>
    </div>
    <div class="qr_center">
      <canvas id="canvass"></canvas>
    </div>
    </div>
  </div>
</template>

<script>
  import QRCode from 'qrcode'
  export default {

    // components: {ElButton},
    data() {
      return {
        msg: '江南无所有、聊赠一枝春',
        txt:""
      }
    },
    mounted(){
      this.useqrcode(this.msg)
    },
    methods: {
      useqrcode(txt) {
        //生成的二维码内容,可以添加变量
        var canvas = document.getElementById('canvass')
        QRCode.toCanvas(canvas, txt, error=>{
          if (error) console.error(error)
        })
      }
      ,
      create(){
        if(!this.txt&&this.txt!="0"){
          this.$message('请输入生成值');
        }else{
          this.useqrcode(this.txt)
          this.$message({
            message: '恭喜你,生成成功',
            type: 'success'
          });
        }
      }
    }
  }

</script>

<style>
  #canvass{
    height: 500px!important;
    width: 500px!important;
  }
  *{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  body,html{
    height: 100%;
  }
  .all{
    height:100%;
    width:100%;
    padding:1% 2%;
  }
  .QR_switchover{
    height: 80px;
    background-color: #ffffff;
    /*box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);*/
    line-height: 80px;
    padding-left:2%;
    font-size:1.8em;
  }
  .qr_center{
    background-color: #fff;
    margin-top: 2%;
    text-align: center;
  }
  .QRCode_seek{
    padding: 2% 3%;
    background-color: #fff;
  }
  .QRCode_seek>div{
    display: inline-block;
  }
  .QRCode_seek>div:last-child{
    margin-left: 2%;
  }

</style>
转载请注明出处或者链接地址:https://www.qianduange.cn//article/13009.html
标签
评论
发布的文章

vue3生成聊天对话框功能

2024-07-10 18:07:36

json基本格式

2024-07-08 09:07:01

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!