目标:将html页面元素转成base64格式的图片。
问题:最初直接用的html2canvas
官网的最新版代码,配置之后保存的图片模糊。
解决方案:采用增加了dpi
和scale
两个选项之后的html2canvas源码,配置这两个参数能得到清晰的图片。
源码地址:https://github.com/eKoopmans/html2canvas/tree/develop/dist
代码配置:
// testImgs是需要转换成图片的页面元素
html2canvas(document.getElementById('testImgs'), {
useCORS: true, //允许跨域
scale: 3,
dpi: 300,
height: $('.testImgs').height() ,
width: $('.testImgs').width(),
backgroundColor: null
}).then(function (canvas) {
var dataUrl = canvas.toDataURL('image/png')
console.log(dataUrl)
})
注意: 在生成图片的元素中所使用的背景图片或者头像等,必须使用img
元素设置,不能使用backgroung
属性,否则图片会变模糊。