官网地址
http://html2canvas.hertzen.com
插件下载地址
https://github.com/niklasvh/html2canvas/releases
引入html2canvas插件
<script src="/js/html2canvas.js"></script>
定义要转换的html(人员实名信息卡)
css:
<style type="text/css">
* {
padding: 0;
margin: 0;
}
.box {
width: 360px;
height: 210px;
background: #295FA2;
border-radius: 10px;
}
.information {
font-size: 16px;
font-weight: bold;
color: #fff;
margin: 0 25px 10px;
padding-top: 12px;
}
.content {
width: 330px;
background: #fff;
margin: 0 auto;
font-size: 6px;
color: #000;
padding-bottom: 10px;
border-radius: 5px;
}
.content_box {
display: flex;
}
.content_title {
color: #999999;
padding: 7px 7px 8px;
}
.content_text div {
margin: 0 7px 6px;
}
.content_text span {
margin-left: 6px;
}
.code {
width: 100px;
height: 100px;
margin: 8px 0 0 50px;
}
.code img {
width: 100%;
}
</style>
html:
<div class="box capture">
<div class="information">人员实名信息卡</div>
<div class="content">
<div class="content_title">xxxx工程局</div>
<div class="content_box">
<div class="content_text">
<div>姓名:<span>张立维</span></div>
<div>班组:<span>水泥机械班班组</span></div>
<div>工种:<span>操作员</span></div>
<div>进厂时间:<span>2021/3/22</span></div>
<div>三级安全教育是否通过:<span>通过</span></div>
</div>
<div class="code">
<img src="/images/code.png" alt="">
</div>
</div>
</div>
</div>
用法
html2canvas(document.getElementsByClassName("capture")[0], {
scale: 2,
allowTaint: false,
useCORS: true,
width: '500',
height: '500',
backgroundColor: '#000000',
}).then((canvas) => {
var imgUri = canvas.toDataURL("image/png");
console.log(imgUri);
});
需要base64转换file也可以加上以下代码
var imgFile = dataURLtoFile(imgUri)
console.log(imgFile)
var formData = new FormData();
formData.append('file', imgFile);
$.ajax({
url: "{{ route('admin.uploadQiniu') }}",
type: 'post',
processData: false,
contentType: false,
data: formData,
success: function (res) {
console.log(res);
}
})
function dataURLtoFile(dataurl, filename = 'file') {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let suffix = mime.split('/')[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
})
}