biji/前端/前端通过页面(dom)生成图片并下载保存 第一版 (模糊).md
2020-02-11 14:13:37 +08:00

52 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

> 遇到一个需要生成海报的需求但是海报又过于复简单的canvas实现太麻烦所以想直接通过dom生成图片。
## 初始准备
用到的库有三个
- ```jquery```
- ```html2canvas```
- ```Canvas2Image```
中间还尝试过一次```dom-to-image```但是出现了错误,没发使用,所以换到了```html2canvas```
## 下载引用
[jquery](https://jquery.com/)
[html2canvas](http://html2canvas.hertzen.com/)
[Canvas2Image](https://github.com/hongru/canvas2image)
引用过程就不做过多描述了
## 使用
页面现在默认已经写好了,通过页面进行生成了
```
//保存脚本是在思否找到的 地址https://segmentfault.com/a/1190000016388897
function downloadimg(imgUrl){
// 如果浏览器支持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()
}
}
$(".download").click(() => {
new html2canvas(document.getElementById('app'), {
allowTaint: true,
taintTest: true,
useCORS: true,
background: null,
windowWidth:document.body.scrollWidth,
windowHeight:document.body.scrollHeight,
x:0,
y:0
}).then(canvas => {
let imgUrl = Canvas2Image.convertToPNG(canvas,$("#app").width(),$("#app").height())
imgUrl = $(imgUrl).attr('src')
downloadimg(imgUrl)
});
})
```