uniapp使用tki-qrcode生成二维码

uniapp使用tki-qrcode生成二维码

导入插件方式一:

1、使用npm下载: 详细属性.方法.事件说明请参照npmjs社区

npm i tki-qrcode

2、页面使用并引入挂载插件:

<view class="qrcode-icon">
    <tki-qrcode ref="qrcode" :val="qrcode" :size="size" :unit="unit" :onval="onval" :load-make="load_make" :show-loading="show_loading" :lv="lv" :background="background" :foreground="foreground" :pdground="pdground" :icon='icon' :iconsize='iconsize' @result="qrR" />
</view>

import tkiQrcode from "tki-qrcode"
export default {
	components: {
		tkiQrcode
	},
    data() {
		return {
			qrcode: 'https://blog.youkuaiyun.com/2201_75870706?type=blog', //二维码的内容链接
			size: 260, //二维码的大小
			unit: 'upx', //大小单位 !!! rpx单位有误
			load_make: true, //组件加载完成后自动生成二维码
			show_loading: false, //是否添加loading
			onval: true, //val值变化时自动重新生成二维码
			background: '#ffffff', //背景色
			foreground: '#000',//点色
			pdground: '#000', //角标色
			icon: 'https://gtms03.alicdn.com/tps/i3/TB1yeWeIFXXXXX5XFXXuAZJYXXX-210-210.png_80x80.jpg', //二维码图标
			iconsize: 30, //二维码图标大小
			lv: 3, //二维码容错级别
			loadingText: '加载中', //loading内容
		}
	},
    methods:{
		qrR(e){
			console.log("生成的图片base64或图片临时地址",e)
		}
	}
}

导入插件方式二:
1、在common文件夹或者components文件夹下新建tki-qrcode文件夹:

<template xlang="wxml" minapp="mpvue">
	<view class="tki-qrcode">
		<!-- #ifndef MP-ALIPAY -->
		<canvas class="tki-qrcode-canvas" :canvas-id="cid" :style="{width:cpSize+'px',height:cpSize+'px'}" />
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
		<canvas :id="cid" :width="cpSize" :height="cpSize" class="tki-qrcode-canvas" />
		<!-- #endif -->
		<image v-show="show" :src="result" :style="{width:cpSize+'px',height:cpSize+'px'}" />
	</view>
</template>
 
<script>
import QRCode from "./qrcode.js"
let qrcode
export default {
	name: "tki-qrcode",
	props: {
		cid: {
			type: String,
			default: 'tki-qrcode-canvas'
		},
		size: {
			type: Number,
			default: 200
		},
		unit: {
			type: String,
			default: 'upx'
		},
		show: {
			type: Boolean,
			default: true
		},
		val: {
			type: String,
			default: ''
		},
		background: {
			type: String,
			default: '#ffffff'
		},
		foreground: {
			type: String,
			default: '#000000'
		},
		pdground: {
			type: String,
			default: '#000000'
		},
		icon: {
			type: String,
			default: ''
		},
		iconSize: {
			type: Number,
			default: 40
		},
		lv: {
			type: Number,
			default: 3
		},
		onval: {
			type: Boolean,
			default: false
		},
		loadMake: {
			type: Boolean,
			default: false
		},
		usingComponents: {
			type: Boolean,
			default: true
		},
		showLoading: {
			type: Boolean,
			default: true
		},
		loadingText: {
			type: String,
			default: '二维码生成中'
		},
	},
	data() {
		return {
			result: '',
		}
	},
	methods: {
		_makeCode() {
			let that = this
			if (!this._empty(this.val)) {
				setTimeout(() => {
					qrcode = new QRCode({
						context: that, // 上下文环境
						canvasId:that.cid, // canvas-id
						usingComponents: that.usingComponents, // 是否是自定义组件
						showLoading: that.showLoading, // 是否显示loading
						loadingText: that.loadingText, // loading文字
						text: that.val, // 生成内容
						size: that.cpSize, // 二维码大小
						background: that.background, // 背景色
						foreground: that.foreground, // 前景色
						pdground: that.pdground, // 定位角点颜色
						correctLevel: that.lv, // 容错级别
						image: that.icon, // 二维码图标
						imageSize: that.iconSize,// 二维码图标大小
						cbResult: function (res) { // 生成二维码的回调
							that._result(res)
						},
					});
				}, 1)
			} else {
				uni.showToast({
					title: '二维码内容不能为空',
					icon: 'none',
					duration: 2000
				});
			}
		},
		_clearCode() {
			this._result('')
			qrcode.clear()
		},
		_saveCode() {
			let that = this;
			if (this.result != "") {
				uni.saveImageToPhotosAlbum({
					filePath: that.result,
					success: function () {
						uni.showToast({
							title: '二维码保存成功',
							icon: 'success',
							duration: 2000
						});
					}
				});
			}
		},
		_result(res) {
			this.result = res;
			this.$emit('result', res)
		},
		_empty(v) {
			let tp = typeof v,
				rt = false;
			if (tp == "number" && String(v) == "") {
				rt = true
			} else if (tp == "undefined") {
				rt = true
			} else if (tp == "object") {
				if (JSON.stringify(v) == "{}" || JSON.stringify(v) == "[]" || v == null) rt = true
			} else if (tp == "string") {
				if (v == "" || v == "undefined" || v == "null" || v == "{}" || v == "[]") rt = true
			} else if (tp == "function") {
				rt = false
			}
			return rt
		}
	},
	watch: {
		size: function (n, o) {
			if (n != o && !this._empty(n)) {
				this.cSize = n
				if (!this._empty(this.val)) {
					this._makeCode()
				}
			}
		},
		val: function (n, o) {
			if (this.onval) {
				if (n != o && !this._empty(n)) {
					this._makeCode()
				}
			}
		}
	},
	computed: {
		cpSize() {
			if(this.unit == "upx"){
				return uni.upx2px(this.size)
			}else{
				return this.size
			}
		}
	},
	mounted () {
		if (this.loadMake) {
			if (!this._empty(this.val)) {
				this._makeCode()
			}
		}
	},
}
</script>
<style>
.tki-qrcode {
  position: relative;
}
.tki-qrcode-canvas {
  position: fixed!important;
  top: -99999upx;
  left: -99999upx;
  z-index: -99999;
}
</style>

2、在tki-qrcode文件夹下新建qrcode.js文件:

let QRCode = {};
(function () {
    /**
     * 获取单个字符的utf8编码
     * unicode BMP平面约65535个字符
     * @param {num} code
     * return {array}
     */
    function unicodeFormat8(code) {
        // 1 byte
        var c0, c1, c2;
        if (code < 128) {
            return [code];
            // 2 bytes
        } else if (code < 2048) {
            c0 = 192 + (code >> 6);
            c1 = 128 + (code & 63);
            return [c0, c1];
            // 3 bytes
        } else {
            c0 = 224 + (code >> 12);
            c1 = 128 + (code >> 6 & 63);
            c2 = 128 + (code & 63);
            return [c0, c1, c2];
        }
    }
    /**
     * 获取字符串的utf8编码字节串
     * @param {string} string
     * @return {array}
     */
    function getUTF8Bytes(string) {
        var utf8codes = [];
        for (var i = 0; i < string.length; i++) {
            var code = string.charCodeAt(i);
            var utf8 = unicodeFormat8(code);
            for (var j = 0; j < utf8.length; j++) {
                utf8codes.push(utf8[j]);
            }
        }
        return utf8codes;
    }
    /**
     * 二维码算法实现
     * @param {string} data              要编码的信息字符串
     * @param {num} errorCorrectLevel 纠错等级
     */
    function QRCodeAlg(data, errorCorrectLevel) {
        this.typeNumber = -1; //版本
        this.errorCorrectLevel = errorCorrectLevel;
        this.modules = null; //二维矩阵,存放最终结果
        this.moduleCount = 0; //矩阵大小
        this.dataCache = null; //数据缓存
        this.rsBlocks = null; //版本数据信息
        this.totalDataCount = -1; //可使用的数据量
        this.data = data;
        this.utf8bytes = getUTF8Bytes(data);
        this.make();
    }
    QRCodeAlg.prototype = {
        constructor: QRCodeAlg,
        /**
         * 获取二维码矩阵大小
         * @return {num} 矩阵大小
         */
        getModuleCount: function () {
            return this.moduleCount;
        },
        /**
         * 编码
         */
        make: function () {
            this.getRightType();
            this.dataCache = this.createData();
            this.createQrcode();
        },
        /**
         * 设置二位矩阵功能图形
         * @param  {bool} test 表示是否在寻找最好掩膜阶段
         * @param  {num} maskPattern 掩膜的版本
         */
        makeImpl: function (maskPattern) {
            this.moduleCount = this.typeNumber * 4 + 17;
            this.modules = new Array(this.moduleCount);
            for (var row = 0; row < this.moduleCount; row++) {
                this.modules[row] = new Array(this.moduleCount);
            }
            this.setupPositionProbePattern(0, 0);
            this.setupPositionProbePattern(this.moduleCount - 7, 0);
            this.setupPositionProbePattern(0, this.moduleCount - 7);
            this.setupPositionAdjustPattern();
            this.setupTimingPattern();
            this.setupTypeInfo(true, maskPattern);
            if (this.typeNumber >= 7) {
                this.setupTypeNumber(true);
            }
            this.mapData(this.dataCache, maskPattern);
        },
        /**
         * 设置二维码的位置探测图形
         * @param  {num} row 探测图形的中心横坐标
         * @param  {num} col 探测图形的中心纵坐标
         */
        setupPositionProbePattern: function (row, col) {
            for (var r = -1; r <= 7; r++) {
                if (row + r <= -1 || this.moduleCount <= row + r) continue;
                for (var c = -1; c <= 7; c++) {
                    if (col + c <= -1 || this.moduleCount <= col + c) continue;
                    if ((0 <= r && r <= 6 && (c == 0 || c == 6)) || (0 <= c && c <= 6 && (r == 0 || r == 6)) || (2 <= r && r <= 4 && 2 <= c && c <= 4)) {
                        this.modules[row + r][col + c] = true;
                    } else {
                        this.modules[row + r][col + c] = false;
                    }
                }
            }
        },
        /**
         * 创建二维码
         * @return {[type]} [description]
         */
        createQrc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值