把页面保存成图片下载
<img :src="imgUrl" alt="" v-show="!firstFlag">
<li class="user-info user-back-li" title="下载图片" @click="setCanvas">
<i class="el-icon-download"></i>
</li>
<div id="capture">...要保存的内容</div>
下载、引入
npm install --save html2canvas
import html2canvas from 'html2canvas'
data() {
return {
imgUrl: '',
firstFlag: true,
};
},
methods中:
saveFile(data, filename) {
const save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
const event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
},
setCanvas () {
let canvas = document.createElement('canvas')
let canvasDom = document.querySelector("#capture")
let width = parseInt(window.getComputedStyle(canvasDom).width)
let height = parseInt(window.getComputedStyle(canvasDom).height)
canvas.width = width * 2
canvas.height = height * 2
canvas.style.width = width / 2 + 'px'
canvas.style.height = height / 2 + 'px'
let context = canvas.getContext('2d')
context.scale(1, 1)
let options = {
canvas: canvas,
useCORS: true
}
html2canvas(canvasDom, options).then(canvas => {
this.imgUrl = canvas.toDataURL("image/png");
this.saveFile(this.imgUrl, new Date().toLocaleString())
this.firstFlag = false;
this.imgUrl = ''
});
},