> 遇到一个需要生成海报的需求,但是海报又过于复,简单的canvas实现太麻烦,所以想直接通过dom生成图片。 ## 初始准备 用到的库有三个 - ```jquery``` - ```html2canvas``` - ```Canvas2Image``` 中间还尝试过一次```dom-to-image```但是出现了错误,没发使用,所以换到了```html2canvas``` ## 下载引用 [jquery](https://jquery.com/) [html2canvas](http://html2canvas.hertzen.com/) [Canvas2Image](https://github.com/hongru/canvas2image) 引用过程就不做过多描述了 ## 使用 页面现在默认已经写好了,通过页面进行生成了 ``` $(".download").click(() => { new html2canvas(document.getElementById('app'), { allowTaint: true, taintTest: true, useCORS: true, background: null, windowWidth:document.body.scrollWidth, windowHeight:document.body.scrollHeight, x:(document.body.scrollWidth - width)/2, y:0 }).then(canvas => { // canvas为转换后的Canvas对象 // imgBlob = canvas.toDataURL('image/jpeg', 1.0); // imgBlob = imgBlob.toString().substring(imgBlob.indexOf(",") + 1); // window.saveAs(imgBlob, 'my-node.png'); let imgUrl = Canvas2Image.convertToPNG(canvas,$("#app").width(),$("#app").height()) console.log($(imgUrl).attr('src')) imgUrl = $(imgUrl).attr('src') // 如果浏览器支持msSaveOrOpenBlob方法(也就是使用IE浏览器的时候),那么调用该方法去下载图片 if (window.navigator.msSaveOrOpenBlob) { var bstr = atob(imgUrl.split(',')[1]) var n = bstr.length var u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } var blob = new Blob([u8arr]) window.navigator.msSaveOrOpenBlob(blob, new Date().getTime() + '.' + 'png') } else { // 这里就按照chrome等新版浏览器来处理 const a = document.createElement('a') a.href = imgUrl a.setAttribute('download', new Date().getTime() + '.png') a.click() } }); }) ```