过去的,终究是过去了
前言
1 介绍
常用配置项
QRCode
{
// 地址信息
text: 'https://static-alias-1.360buyimg.com/jzt/md/images/re-logo.png',
// 二维码宽
width: 100,
// 二维码高
height: 100,
// 二维码亮色
colorDark: '#000000',
// 二维码暗色
colorLight: '#ffffff',
// 纠错等级
// 纠错级别越高,整体需要携带的信息越多
// L : 1, M : 0, Q : 3, H : 2
correctLevel: QRCode.CorrectLevel.H
}
mcanvas
{
// 位置信息
left: 0,
top: 0,
pos: {
x: 'center',
y: 'center',
scale: 0.84,
rotate: 1
},
// 宽高信息
width: '100%',
height:100,
// 文本信息
align: 'center',
normalStyle: {
font: 'italic small-caps bold 24px arial',
color: '#ffffff'
},
// 图片信息
type: 'jpg',
quality: 0.8,
}
常用方法
background
// 背景图
mc.background(path, option)
add
// 主图,装饰图
mc.add(path, option)
text
// 文字
mc.add(text, option)
watermark
// 水印
mc.watermark(path, option)
draw
// 合成
mc.draw(option)
2 使用
安装
npm install qrcodejs2 --save
npm install mcanvas --save
// npm安装不了,切换镜像
npm install mcanvas --save --canvas_binary_host_mirror=https://npm.taobao.org/mirrors/node-canvas-prebuilt/
合成图片
<template>
<div>
<div class="qrcode" ref="qrCodeUrl" v-show="false"></div>
<img :src="b64" />
</div>
</template>
<script>
import { MCanvas } from 'mcanvas'
import QRCode from 'qrcodejs2'
export default {
data() {
return {
isShowBtn: false,
value: 10,
b64: ''
}
},
mounted() {
this.creatQrCode().then(() => {
// 使用nextTick无法获取到实例
// 必须使用 setTimeout 延迟
setTimeout(this.init, 0)
})
},
methods: {
init() {
const mc = new MCanvas({
width: 500,
height: 500,
backgroundColor: 'black'
})
// background : 准备底图;提供多种模式
mc.background(
'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3744052883,4237116621&fm=26&gp=0.jpg',
{
left: 0,
top: 0,
color: '#000000',
type: 'origin'
}
)
// add 添加图片素材基础函数;
mc.add(
'https://img1.360buyimg.com/n6/jfs/t1/170673/4/2913/244729/6002af29E86fbc8f4/a678f2fedc23b5cc.jpg',
{
width: 160,
pos: {
x: 'center',
y: 'center',
scale: 0.84,
rotate: 1
}
}
)
// text 添加文字数据基础函数;
mc.text('落霞与孤鹜齐飞<br>秋水共长天一色', {
// width: '300px',
// align: 'center',
normalStyle: {
font: 'italic small-caps bold 24px arial',
color: '#ffffff'
},
pos: {
x: '40%',
y: 0
}
})
// watermark 添加水印函数,基于 add 函数封装;
mc.watermark(this.$refs.qrCodeUrl.querySelector('img').src, {
width: 60,
pos: 'rightBottom'
})
// draw 最终绘制函数,用于最终的绘制;
mc.draw({
type: 'jpg',
quality: 0.8,
success: b64 => {
console.log('b64', b64)
},
error: err => {
console.log('b64', err)
}
}).then(b64 => {
this.b64 = b64
})
},
creatQrCode() {
const qrcode = new QRCode(this.$refs.qrCodeUrl, {
text: 'https://static-alias-1.360buyimg.com/jzt/md/images/re-logo.png',
width: 100,
height: 100,
colorDark: '#000000',
colorLight: '#ffffff',
// 纠错等级
// 纠错级别越高,整体需要携带的信息越多
// L : 1, M : 0, Q : 3, H : 2
correctLevel: QRCode.CorrectLevel.H
})
console.log('qrcode', qrcode)
return Promise.resolve(qrcode)
}
}
}
</script>
<style lang="scss" scoped></style>
3.注意
1.npm 无法安装mcanvas时,切换镜像源
2.等待二维码渲染完成,在settimeout延迟后才能获取DOM二维码图片地址
尾声
别担心,我在呢,一切都会好起来的
晚安 ^_^