html2canvas 生成图片,转二进制
<div id="hidden-poster" class="canvas" style="position: absolute; left: -9999px;">
<img style="width:800px;" class="" src="https://xxxfwxm_bg.png"/>
<p class="text1 text-overlay"></p>
<p class="text5 text-overlay"></p>
<p class="text2 text-overlay"></p>
<p class="text3 text-overlay"></p>
<p class="text4 text-overlay"></p>
</div>
html2canvas只对dom节点有效 所以在页面加入hidden-poster元素用于生成canvas,
和p需要再画布指定地方生成的文本。
//html2canvas
generateImage() {
this.dialogLoading=true;
const element = document.getElementById('hidden-poster');
const text1 = document.querySelector('.text1');
const text2 = document.querySelector('.text2');
const text3 = document.querySelector('.text3');
const text4 = document.querySelector('.text4');
const text5 = document.querySelector('.text5');
text1.innerHTML=this.formLabelAlign.projectName +','+ '<span style="color:#333;">怎么办?<span>';
text2.innerHTML=this.formLabelAlign.servedPopulation;
text3.innerHTML=this.formLabelAlign.serviceItems;
text4.innerHTML=this.formLabelAlign.serviceSpecifications;
text5.innerHTML=this.formLabelAlign.medicalCareServices;
//这里由于每个文本位置是固定的就直接写成固定画布显示的位置
text1.style.left = 230 + 'px';
text1.style.top = 126 + 'px';
text2.style.left = 104 + 'px';
text2.style.top = 1060 + 'px';
text3.style.left = 105 + 'px';
text3.style.top = 1245 + 'px';
text4.style.left = 515 + 'px';
text4.style.top = 1245 + 'px';
text5.style.left = 48 + 'px';
text5.style.top = 804 + 'px';
html2canvas(element, {
useCORS: true, // 重要:如果图片来自外部域,需要此选项[citation:3][citation:6]
scale: window.devicePixelRatio || 1, // 提高高清屏下的清晰度[citation:6]
backgroundColor: null // 背景透明,以显示图片本身
}).then(canvas => {
// 将生成的Canvas转换为图片并显示
const dataUrl = canvas.toDataURL('image/png');
this.formLabelAlign.canvasUrl=dataUrl;
// 转2进制
canvas.toBlob(async(blob) => {
// Blob就是二进制对象,可直接用于:
// 可选:转为ArrayBuffer(二进制缓冲区,更灵活的操作)
const arrayBuffer = await blob.arrayBuffer();
// console.log('ArrayBuffer长度:', arrayBuffer.byteLength);
// 可选:转为FormData(用于接口上传文件)
const formDatas = new FormData();
console.log(blob);
formDatas.append('file', blob, 'canvasImg.png'); // 第三个参数是文件名
// console.log('FormData(可直接上传):', formData);
const params={
url:this.canvasUpload,
methods:'POST',
data:formDatas
}
this.sendReq(params, (res) => {
this.formLabelAlign.canVasImgUrl=res.data.url;
this.dialogLoading=false;
}).catch(err=>{
this.dialogLoading=false;
})
// 验证:预览生成的图片(可选)
// const previewUrl = URL.createObjectURL(blob);
// document.getElementById('finalImage').src=previewUrl;
this.canvasUpload=this.canvasUpload+=previewUrl;
}, 'image/png'); // 这里指定格式为PNG,如需JPG则改为 'image/jpeg', 0.9(质量)
// 这里你也可以将dataUrl上传到服务器[citation:4]
}).catch(error => {
console.error('截图失败:', error);
});
},
html2canvas生成图片并转为二进制上传服务器
最新推荐文章于 2025-12-28 09:15:48 发布
2911

被折叠的 条评论
为什么被折叠?



