安装
npm i qrcodejs2
npm i html2canva
引入
import saveQRcode from "@/utils/saveQRcode";
import QRCode from "qrcode";
import html2canvas from "html2canvas";
saveQRcode
方法请前往画布(canvas)图像保存成本地图片
使用
样式图片
样式图片
html
<template>
<div class="main">
<!-- 海报html元素 -->
<div class="content">
<div id="posterHtml" class="poster">
<div class="product-pic">
<img src="@/assets/images/lxsc.jpg" alt />
</div>
<div class="product">
<!-- 底部标题 -->
<div class="product-info">
<p class="product-info-sign">餐饮食材供应商</p>
</div>
<!-- 底部红色提示 -->
<div class="product-info">
<p class="product-info-name">{{ product.detailTitle }}</p>
</div>
<!-- 二维码 -->
<div class="qrcode">
<canvas ref="qrcodeImg"></canvas>
</div>
</div>
</div>
<van-button class="btn-down" size="small" round @click="createPoster">点击保存</van-button>
</div>
</div>
</template>
js
data() {
return {
posterContent: "冷鲜食品商城",
product: {}
};
},
mounted() {
this.createQrcode();
},
methods: {
createQrcode(text) {
// 生成二维码
let codeLink = window.location.protocol + "//" + window.location.host;
var canvas = this.$refs.qrcodeImg;
QRCode.toCanvas(canvas, codeLink, error => {
if (error) console.error(error);
});
},
createPoster() {
// 生成海报
const domObj = document.getElementById("posterHtml");
html2canvas(domObj, {
useCORS: true, // 防止跨域,效果并不好
allowTaint: false,
logging: false,
letterRendering: true,
onclone(doc) {
let e = doc.querySelector("#posterHtml");
e.style.display = "block";
}
}).then(function(canvas) {
// 保存 canvas
saveQRcode(canvas.toDataURL("image/png"));
});
},
}
css
.main {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .7);
overflow: hidden;
.content {
position: fixed;
left: 50%;
top: 50%;
width: 75%;
transform: translate(-50%, -50%);
.poster {
width: 100%;
border-radius: 8px;
overflow: hidden;
background-color: white;
.product-pic {
width: 100%;
max-height: 280px;
min-height: 150px;
overflow: hidden;
img {
width: 100%;
}
}
.product {
display: flex;
justify-content: space-between;
padding: 0 20px 10px 20px;
.product-info {
display: flex;
flex-direction: column;
justify-content: space-around;
.product-info-name {
font-size: 14px;
color: #333;
}
.product-info-price {
padding: 0 10px;
background-color: #f33;
font-size: 18px;
color: white;
text-align: center;
border-radius: 10px;
}
.product-info-sign {
padding: 0 4px;
background-color: #f33;
font-size: 12px;
color: white;
text-align: center;
}
}
}
}
.btn-down {
position: absolute;
left: 50%;
bottom: -50px;
transform: translateX(-50%);
}
}
}
.order-share {
border: 1px solid #ff6f6f;
height: 30px;
padding: 0 8px;
margin-top: 5px;
background: white;
color: #ff6f6f;
line-height: 30px;
border-radius: 4px;
}