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