因为将图片设置为背景,需要往框里填入动态二维码,但因手机像素大小不同导致兼容性很差,所以就使用图片加文字加二维码的形式直接生成图片。
使用插件:html2canvas.js
1.首先写好界面布局
css:
* {
margin: 0px;
padding: 0px;
}
.container {
display: flex;
flex-direction: column;
}
.header{
width:100%;
}
.img {
width: 100%;
}
.body {
display: flex;
flex-direction: row;
justify-content: space-around;
}
.item1 {
flex-grow: 2;
word-break: break-all;
margin-top: 5px;
}
.item2 {
flex-grow: 1;
text-align: center;
margin-top: 10px;
margin-right: 10px;
}
.title {
margin-bottom: 10px;
}
.titleHeader {
background: rgb(243, 140, 5);
color: white;
padding: 3px;
border-radius: 5px;
font-weight: bold;
font-size: 15px;
}
.titleBody {
font-weight: bold;
font-size: 15px;
line-height: 22px;
}
.tips {
display: flex;
flex-direction: row;
justify-content: space-between;
margin-bottom: 5px;
}
.tipsStyle {
background: rgb(231, 129, 129);
padding: 3px;
border-radius: 5px;
color: white;
font-size: 10px;
margin-left:10px;
}
html:
<div class="container">
<div class="header">
<img class="img" src="" alt="图片加载中,请稍后">
</div>
<div class="body">
<div class="item1" style="padding: 10px;">
<div class="title">
<span class="titleHeader">职位名称</span> <span class="titleBody"></span>
</div>
<div class="title">
<span class="titleHeader">综合工资</span> <span class="titleBody"></span>
</div>
<div class="title">
<span class="titleHeader">职位亮点</span> <span class="titleBody"></span>
</div>
<div class="title">
<span class="titleHeader">工作地址</span> <span class="titleBody"></span>
</div>
</div>
<div class="item2">
<div id="container">
<canvas width="100" height="100"></canvas>
</div>
<p style="font-size:14px;color:rgb(110, 110, 110);">长按识别保存</p>
</div>
</div>
<div class="tips">
<div class="tipsStyle">实名认证/3免服务/10万授信</div>
</div>
</div>
<img class="imgDownload" src="" style="width:100%;">
布局好了,大概样式是这样的:
可以看见,目前还是Dom元素。
在JS中,我们先将Dom元素转为canvas,然后使用toDataURL()方法转换成base64码图片。
//第一步,我们先生成二维码
$("#container").erweima({
quiet: 1,
mode: 0,
mSize: 20,
background: "#fff",
fill: "black",
radius: 0,
size: 105,
text: "XXXXX"
});
//获取需要转化成canvas的dom对象
var saveDom = $(".container")[0];
使用html2canvas转化成canvas
html2canvas(saveDom).then(function (canvas) {
//将canvas转化成base64图片
var tempSrc = canvas.toDataURL("image/png");
//将base64传给img标签
$(".imgDownload").attr("src", tempSrc);
//删除Dom节点
$(".container").remove();
});
因为是在微信端使用,所以长按保存即可打开微信保存图片按钮。
在手机浏览器可以长按保存,也可以写a标签点击下载(微信端限制不可用)。