html2canvas html2canvas
基本使用
import html2canvas from 'html2canvas'
html2canvas (document .body ).then (function (canvas ) { let dataURL = canvas.toDataURL ('image/png' ) })
常用配置使用示例
var options = { dpi : 192 , scale : 2 , useCORS : true } html2canvas (document .querySelector ('#app' ), options).then (canvas => { document .body .appendChild (canvas) })
html2canvas 生成图片模糊问题
html2canvas 第二个参数配置 scale
和 dpi
, 参考
如果要生成的 dom 中有背景图片,将背景图片换成 div 包裹 img 标签形式,不要通过css设置成background
dom-to-image dom-to-image
基本使用
import domtoimage from 'dom-to-image' var domtoimage = require ('dom-to-image' )
var node = document .getElementById ('my-node' )domtoimage .toPng (node) .then (function (dataUrl ) { var img = new Image () img.src = dataUrl document .body .appendChild (img) }) .catch (function (error ) { console .error ('oops, something went wrong!' , error) })
将 base64 转换成 file 对象用于上传到服务器
b64ToFile (dataurl ) { let arr = dataurl.split (',' ) let mime = arr[0 ].match (/:(.*?);/ )[1 ] let bstr = atob (arr[1 ]) let n = bstr.length let u8arr = new Uint8Array (n) while (n--) { u8arr[n] = bstr.charCodeAt (n) } let file = new File ([u8arr], 'filename.png' , {type :mime}) }