html2canvas.js + qrcode.js 微信海报生成二维码图片,并处理了canvas生成图片模糊的问题
使用插件:jQuery html2canvas qrcode
效果图:![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e0a99a75092465a390e45b7c31ee012b.png#pic_center)
代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>海报demo</title>
<style>
*{margin: 0;padding: 0;}
#app{background: olivedrab;height: 100vh;}
.box{position: relative;z-index: -1;}
.box .back{width: 100%;height: 100%;position: absolute;left: 0;top: 0;}
#qrcode{position: absolute;left: 122px;top: 220px;z-index: 9;}
.PostersImg{width: 344px;height: 344px;position: absolute;left: 0;right: 0;top: 0;bottom: 0;display: none;margin: auto;}
.PostersImg img{width: 100%;}
</style>
</head>
<body>
<div id="app">
<div class="box" style="width: 344px;height: 344px;">
<img class="back" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.qiantucdn.com%2F58pic%2F27%2F08%2F16%2F02K58PICkMZ_1024.jpg%21%2Ffw%2F1024%2Fwatermark%2Furl%2FL2ltYWdlcy93YXRlcm1hcmsvZGF0dS5wbmc%3D%2Frepeat%2Ftrue%2Fcrop%2F0x1009a0a0&refer=http%3A%2F%2Fpic.qiantucdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636881952&t=82b986a73cb74e89fed14d7f5d73d315" alt="">
<div id='qrcode'></div>
</div>
<div class="PostersImg">
<img src="" alt="">
</div>
<input type="button" value="生成画报" style="margin-left: 150px;margin-top: 20px;" onclick="addImg()"/>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/qrcode.js"></script>
<script src="js/html2canvas.js"></script>
<script>
var qrcode = new QRCode("qrcode", {
text: "http://www.baidu.com",
width: 100,
height: 100,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
function addImg(){
var copyDom = document.querySelector('.box');
var width = copyDom.offsetWidth;
var height = copyDom.offsetHeight;
var canvas = document.createElement("canvas");
var scale = 3;
canvas.width = width * scale;
canvas.height = height * scale;
canvas.getContext("2d")
var context = canvas.getContext('2d');
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
var opts = {
scale: scale,
canvas: canvas,
width: width,
height: height,
dpi:300,
useCORS: true,
};
html2canvas(copyDom, opts).then(canvas => {
canvas.setAttribute("crossOrigin",'anonymous');
let dataURL = canvas.toDataURL("image/png");
$('.PostersImg img').attr('src', dataURL);
$('.PostersImg').show()
});
}
</script>
</body>
</html>