`
<head> <title>二维码生成</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" /> <script type="text/javascript" src="https://cdn.staticfile.net/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/qrcodejs/1.0.0/qrcode.js"></script> </head> <style> .box { height: 100%; width: 100%; margin: 0 auto; padding: 20px; }#submit-btn {
margin-left: 15px;
}
#text {
width: 300px;
}
#qrcode {
margin-top: 25px;
height: 100px;
width: 100px;
}
<body>
<div class="box">
<textarea id="textarea" name="textarea" rows="5" cols="170" placeholder="请输入生成二维码的数据"></textarea>
<button id="submit-btn">生成二维码</button>
<button id="download-btn" disabled>下载</button><br />
<div id="qrcode"></div>
<canvas id="canvas" style="display:none;"></canvas>
</div>
<script type="text/javascript">
var str = { "po": "SPW-456"}
var dom = document.getElementById("qrcode")
var elTextarea = document.getElementById("textarea");
var canvas = document.getElementById("canvas");
var downloadBtn = document.getElementById("download-btn");
var ctx = canvas.getContext("2d");
elTextarea.value = JSON.stringify(str)
var qrcode = new QRCode(dom, {
width: 500,
height: 500,
// correctLevel: QRCode.CorrectLevel.L // 尝试降低纠错级别
});
$("#submit-btn").off("click").on("click", () => {
if (!elTextarea.value) {
downloadBtn.disabled = true;
alert("请输入文本!");
return false;
}
try {
qrcode.makeCode(elTextarea.value);
downloadBtn.disabled = false; // 生成成功后启用下载按钮
} catch (error) {
alert("生成二维码出错:" + error.message);
downloadBtn.disabled = false; // 启用下载按钮以便用户可以重试
}
})
$("#download-btn").off("click").on("click", function () {
canvas.width = qrcode._oDrawing._elImage.width;
canvas.height = qrcode._oDrawing._elImage.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(dom.querySelector("img"), 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL("image/png");
var downloadLink = document.createElement("a");
downloadLink.href = dataURL;
downloadLink.download = "二维码.png";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
</script>
</body>
`
标签:canvas,downloadLink,前端,导出,height,width,二维码,var,document
From: https://www.cnblogs.com/33shan/p/18099663