Vue海报二维码组合图片生成和下载-qrcodejs2-html2canvas
项目核心完整代码-下载
演示
安装
npm install qrcodejs2 --save
npm install html2canvas --save
核心代码-具体页面结构请看完整代码
//项目中使用 - 需要的地方直接引入使用即可
import QRCode from "qrcodejs2";
import html2canvas from "html2canvas";
//二维码生成
/**
* @description 生成二维码
* @param {number} qWidth 宽度
* @param {number} qHeight 高度
* @param {string} qText 二维码内容(跳转连接)
* @param {string} qRender 渲染方式(有两种方式 table和canvas,默认是canvas)
*/
qrcode(qWidth, qHeight, qText, qRender) {
// 清空二维码
this.$refs.qrCodeDiv.innerHTML = "";
new QRCode(this.$refs.qrCodeDiv, {
width: qWidth,
height: qHeight,
text: qText,
render: qRender,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.L,
});
},
// 生成海报
cancel() {
const dialog = this.$refs.dialog;
this.createQrCodePic();
window.pageYOffset = 0;
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
html2canvas(this.$refs.dialog, {
useCORS: true, //设置为true,避免图片产生跨域
logging: true,
allowTaint: false,
width: dialog.offsetWidth,
height: dialog.offsetHeight,
scale: window.devicePixelRatio || 1,
backgroundColor: null,
}).then((canvas) => {
let dataURL = canvas.toDataURL("image/png");
console.log("dataURL", dataURL);
this.htmlUrl = dataURL;
});
},
// 下载图片
downloadBtn() {
var link = document.createElement("a");
link.href = this.htmlUrl;
console.log(link.href);
link.download = "poster-download.png";
setTimeout(() => {
link.click();
}, 1000);
},
import html2canvas from "html2canvas";
/**
* 保存html2Canvas的图片到本地
* @param element html2canvas关联的ref,传ref.value进来
* @param backgroundColor 保存的图片背景颜色
* @param imgName // 保存的图片名称,默认Share-ABCD
*/
export function saveHtml2CanvasImage(element, {
backgroundColor='#24282D',
imgName='Share-ABCD',
}) {
const scale = window.devicePixelRatio;
const {clientWidth, clientHeight} = element;
return html2canvas(element, {
scale,
width: clientWidth,
height: clientHeight,
scrollX: 0,
scrollY: 0,
backgroundColor: backgroundColor,
}).then((canvas) => {
const imgUrl = canvas.toDataURL('image/png');
const tempLink = document.createElement('a');// 创建一个a标签
tempLink.style.display = 'none';
tempLink.href = imgUrl;
tempLink.setAttribute('download', imgName);
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);// 将a标签添加到body当中
tempLink.click();// 启动下载
document.body.removeChild(tempLink);// 下载完毕删除a标签
window.URL.revokeObjectURL(imgUrl);
});
}
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634101.html