使用qrcodejs前端生成二维码
官网
Github: https://github.com/davidshimjs/qrcodejs
qrcode.js原理是用html5 Canvas画布生成二维码.
步骤: 先将文字转换为二维码图片,在把二维码图片转为base64字符串
使用
<div id="qrcode"></div>
<script type="text/javascript">
//这里声明为全局变量即可
var qrcode = new QRCode(document.getElementById("qrcode"), {
text: "http://jindo.dev.naver.com/collie",
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
//其他操作
qrcode.clear(); // clear the code.
//makeCode会看到canvas画布的图片,但是base64的字符串还没有生成,所以要下载尽量先预览再下载
qrcode.makeCode("http://naver.com"); // make another code.
</script>
下载二维码
直接下载(无文件后缀)
把生成的base64二维码的开头data:image/png;base64 改成 data:application/octet-stream;base64即可 ,但是这样下载的文件没有后缀
var base64Str = $('#qrcode > img').attr('src');
var base64 = base64Str.replace("data:image/png;base64,",'data:application/octet-stream;base64,');
window.location.href = 'data:application/octet-stream;base64,' + img;
模拟超链接下载base64二维码
// 这里是获取到的图片base64编码,这里只是个例子哈,要自行编码图片替换这里才能测试看到效果
const imgUrl = 'data:image/png;base64,...'
// 如果浏览器支持msSaveOrOpenBlob方法(也就是使用IE浏览器的时候),那么调用该方法去下载图片
if (window.navigator.msSaveOrOpenBlob) {
var bstr = atob(imgUrl.split(',')[1])
var n = bstr.length
var u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
var blob = new Blob([u8arr])
window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
} else {
// 这里就按照chrome等新版浏览器来处理
const a = document.createElement('a')
a.href = imgUrl
a.setAttribute('download', 'chart-download')
a.click()
}
下载为指定名称
<a download="FILENAME.EXT" href="data:image/png;base64,asdasd...">Download</a>
文字转为图片形式的文字
不使用二维码,直接把文字转换为图片形式的文字
function textBecomeImg(text,fontsize,fontcolor){
var canvas = document.createElement('canvas');
//小于32字加1 小于60字加2 小于80字加4 小于100字加6
$buHeight = 0;
if(fontsize <= 32){ $buHeight = 1; }
else if(fontsize > 32 && fontsize <= 60 ){ $buHeight = 2;}
else if(fontsize > 60 && fontsize <= 80 ){ $buHeight = 4;}
else if(fontsize > 80 && fontsize <= 100 ){ $buHeight = 6;}
else if(fontsize > 100 ){ $buHeight = 10;}
//对于g j 等有时会有遮挡,这里增加一些高度
canvas.height=fontsize + $buHeight ;
var context = canvas.getContext('2d');
// 擦除(0,0)位置大小为200x200的矩形,擦除的意思是把该区域变为透明
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = fontcolor;
context.font=fontsize+"px Arial";
//top(顶部对齐) hanging(悬挂) middle(中间对齐) bottom(底部对齐) alphabetic是默认值
context.textBaseline = 'middle';
context.fillText(text,0,fontsize/2)
//改变大小后,重新设置一次文字
canvas.width = context.measureText(text).width;
context.fillStyle = fontcolor;
context.font=fontsize+"px Arial";
context.textBaseline = 'middle';
context.fillText(text,0,fontsize/2)
var dataUrl = canvas.toDataURL('image/png');//注意这里背景透明的话,需要使用png
return dataUrl;
}
// 使用
textBecomeImg("啦啦啦",50,"#000");
如果这篇文章对你有用,可以关注本人微信公众号获取更多ヽ(^ω^)ノ ~
![微信公众号二维码](https://images.cnblogs.com/cnblogs_com/aeolian/1679458/o_wechat_gzh_qrcode.jpg)