最近项目叫做一个收款码的生成,如下图,因为二维码是动态生成的,所以整张图片需要自己拼接,然后搞成图片下载下来,
所以就尝试用canvas做了,首部是提示信息,然后是扫码支持的方式,店铺名称,二维码,二维码上面还有个收钱的小标志,最好就是公司的logo了。哈哈,上代码了
代码如下:
var app = new Vue({
el: '#app',
data: {
imgs: {
scanimg: './images/scan.png',
mongyimg: './images/mongy.png',
jllogoimg: './images/jingjia-logo.png',
wechatimg: './images/wechat.png',
alipayimg: './images/alipay.png',
qrcodeimg: './images/qrcode.png'
},
promise_all: []
},
methods: {
bulidCode() {
this.drawImg({
shop_name: '辣姑娘麻辣烫',
device_no: '5205978456nc'
})
},
drawImg(row) {
const _t = this
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
// 绘制电子牌背景色
ctx.fillStyle = 'rgba(251,251,251,1)'
ctx.fillRect(0, 0, 750, 1200)
// 绘制头部背景色
ctx.fillStyle = '#2f91cf'
ctx.fillRect(0, 0, 750, 176)
// 绘制头部文字
_t.promise_all.push(drawImageFn(ctx, _t.imgs.scanimg, 150, 52, 450, 70))
// 绘制支付方式
drawPayFn(ctx)
// 绘制文字
drawTextFn(ctx, {
font: '28px sans-serif',
text: row.shop_name,
color: '#2f91cf',
y: 404,
w: 600
})
// 绘制二维码
_t.promise_all.push(drawImageFn(ctx, _t.imgs.qrcodeimg, 176, 450, 400, 400))
// 绘制二维码logo
_t.promise_all.push(drawImageFn(ctx, _t.imgs.mongyimg, 332, 606, 90, 90))
// 绘制文字
drawTextFn(ctx, {
font: '24px sans-serif',
text: row.device_no,
color: '#ada5a6',
y: 892
})
_t.promise_all.push(drawImageFn(ctx, _t.imgs.jllogoimg, 276, 940, 200, 48))
// 绘制文字
// 绘制图片函数
function drawImageFn(ctx, url, x, y, w, h) {
return new Promise(function (resolve, reject) {
var img = new Image()
img.src = url
img.onload = function () {
ctx.drawImage(img, x, y, w, h)
if (img.complete) {
resolve(true)
} else {
reject(new Error('no lyric'))
}
}
})
}
// 绘制支付方式
function drawPayFn(ctx, payType) {
_t.promise_all.push(drawImageFn(ctx, _t.imgs.wechatimg, 150, 208, 66, 66))
drawTextFn(ctx, {
font: '20px sans-serif',
text: '微信支付',
color: '#8e8e8e',
x: 184,
y: 320
})
_t.promise_all.push(drawImageFn(ctx, _t.imgs.alipayimg, 514, 208, 66, 66))
drawTextFn(ctx, {
font: '20px sans-serif',
text: '支付宝',
color: '#8e8e8e',
x: 546,
y: 320
})
}
// canvas 转换成图片
function canvasToImg(canvas) {
var image = new Image()
image.src = canvas.toDataURL('image/png')
return image
}
// 绘制文字
function drawTextFn(ctx, data) {
ctx.font = data.font
ctx.textAlign = 'center'
ctx.fillStyle = data.color || '#333'
var x = data.x || 376
if (data.w) {
ctx.fillText(data.text, x, data.y, data.w)
} else {
ctx.fillText(data.text, x, data.y)
}
}
}
},
})