快捷搜索:  汽车  科技

vue识别二维码内容(vue中动态生成二维码)

vue识别二维码内容(vue中动态生成二维码)}); this.getCode();还有两个问题我提醒一下孩子们:1,如果二维码是在弹框中,this.$nextTick (function () {

接上一篇:【一】vue中动态生成二维码

上一篇遗留的问题是:

渲染出来的是table点块(原谅我眼瞎,这个问题是我帮别人解决问题给做的demo并没有细看),导致后面有一个功能:长安图片保存到本地,或者长按识别不了。

vue识别二维码内容(vue中动态生成二维码)(1)


正确的姿势是:渲染成canvas,通过canvas的方法toDataURL生成base64的路径赋值给img标签就可以展示了!

还有两个问题我提醒一下孩子们:

1,如果二维码是在弹框中,

this.$nextTick (function () {

this.getCode();

});

是要写在弹框执行的里面的。

2,toDataURL是在确保页面渲染出canvas之后才能用的,所以你可能需要一个promise语法去保证。好了,最终的解决方案如下(请忽略我的命名及一些规范性的东西,时间紧,多人合作,没法去改别人的命名):

A.html

<!-- canvas二维码 -->

<div class="codeStyle" id="code" ref="code"></div>

<!--image形式的二维码-->

<div class="codeStyle bannerwechat " id="wecode" ></div>

B.canvas二维码的渲染

getCode(){

var p =new Promise(function(resovle reject){

var date = new Date().getTime();//二维码后面加个时间戳,避免缓存

var qrcode = $("#code").qrcode({

render: "canvas" //canvas

width: 200 //宽度

height:200 //高度

text:`www.baidu.com?date=${date}` //自定义拼写

});

console.log('创建的canvas' qrcode)

resovle(qrcode);

})

return p

}

C.把canvas转化为img的url,并渲染到页面上

getImgUrl(){

var p = new Promise(function(resovle reject){

var canvas = document.getElementsByTagName('canvas')[0];

console.log('获取到的canvas' canvas)

var image = new Image();

//将转换后的img标签插入到html中

image.src = canvas.toDataURL("image/png");

$('#code').fadeOut();

console.log('创建图片' image)

$('.bannerwechat').append(image)

resovle(image)

})

return p

}

D,方法串串烧,执行以上两种方法

this.$nextTick (function () {

this.getCode()

.then(this.getImgUrl)

});

好了,完美。


结果如下:

vue识别二维码内容(vue中动态生成二维码)(2)

猜您喜欢: