前端代码实现保存图片到本地

需求

查看个人简历后,可以点击生成简历图片并保存到本地,也就是根据HTML代码在前端生成图片,而不需要经过后台处理!

html2canvas

在google上搜索该功能需求,提到最多的就是 html2canvas。大致看了一下官网文档,使用方法也比较简单:

1
2
3
html2canvas(document.querySelector("#capture")).then(canvas => {
document.body.appendChild(canvas)
});

然后分别在PC端和手机端查看效果,PC端可以正常显示,但是手机端却无效!继续搜索发现一篇文章 H5实现保存图片的踩坑记录。文章内容比较详细,而我要的功能又不需要那么复杂。所以只应用了核心代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
function snapshot(){
$('#snapshot').hide(); # 隐藏“生成图片”按钮,否则会在生成的图片头部有空白区域
const el = document.querySelector('#capture')
html2canvas(el).then(canvas => {
const img = new Image()
img.style.display = "block"
// 将 canvas 导出成 base64
img.src = canvas.toDataURL('image/jpeg')
// 添加图片到预览
//document.querySelector('#preview').appendChild(img)
$('#capture').html(img);
})
}

其他功能陆续使用的时候再继续更新。。。