效果图
原理
将div(海报内容)转换成图片,显示给用户的海报就是这张图片,用户即可在手机端用手机的保存图片方法保存海报。
方法步骤
设置一个img元素和div(海报内容)同级,样式调整到覆盖在div(海报内容)上,在加载海报页面时将div(海报内容)用html2canvas转为图片,可以得到海报图片url,再通过js操作把已设置的img元素的src属性赋值为刚刚得到的url,用户在手机端下载海报时就可以下载这张得到的海报图片了。
代码
html
<div style="width: 100vw; height: 100vh;; background-color: darkgray; text-align: center;">
<img id="qr-code-img" src="" style="position: fixed; z-index: 20; top: calc(100vh - 607px);left: calc((100vw - 288px) / 2); width: 288px; height: 372px; border-radius: 12px;">
<div
id="qr-code"
style="position: fixed; z-index: 10; top: calc(100vh - 607px); left: calc((100vw - 288px) / 2); width: 288px; height: 372px; border-radius: 12px; background:url('./img/share_bg.png') no-repeat; background-size: 100% 100%;"
>
<div style="height:66px; line-height: 22px; margin-bottom: 24px;">
<span style="max-width: 240px; padding: 24px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2;">海报标题</span>
</div>
<div><img style="width: 200px; height: 200px; filter: drop-shadow(0px 4px 12px #99E0FF); border-radius: 12px" src="./img/qrcode.png"></div>
<div style="margin-top: 16px;">长按识别二维码</div>
</div>
<div style="position: fixed; z-index: 1; top: calc(100vh - 326px); height: 326px; width: 100vw; background-color: #fff; padding-top: 108px;">
<div>
<span style="width: 44px; height: 1px; display: inline-block; background: #F0F0F0;margin: 4px 12px;"></span>
长按图片保存
<span style="width: 44px; height: 1px; display: inline-block; background: #F0F0F0;margin: 4px 12px;"></span>
</div>
<div style="height: 132px; margin-top: 16px;">
海报其他内容
</div>
</div>
</div>
js
import html2canvas from 'html2canvas';
initChangeToImg();
function initChangeToImg() {
const $qrCodeImg = document.getElementById('qr-code-img');
html2canvas(document.getElementById('qr-code'), {
scale: 2.605,
useCORS: true,
backgroundColor: 'transparent',
}).then((canvas) => {
const dataURL = canvas.toDataURL('image/png');
$qrCodeImg.attr('src', dataURL);
});
}