将html生成图片
需求
工具
安装
npm install --save html2canvas
导入
import html2canvas from 'html2canvas'
使用
- 绘制html区域
<div id="informBrand">测试</div>
<a-button type="primary" icon="download" @click="download">导出</a-button>
- 下载方法
download(){
const canvas2 = document.createElement('canvas');
let _canvas = document.getElementById('informBrand');
const w = parseInt(window.getComputedStyle(_canvas).width);
const h = parseInt(window.getComputedStyle(_canvas).height);
//将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
canvas2.width = w * 2;
canvas2.height = h * 2;
const context = canvas2.getContext('2d');
context.scale(1, 1);
window.scrollTo(0, 0); //这一步是必须的 不然下载的图片会出现偏移
html2canvas(_canvas, { canvas: canvas2 }).then(function(canvas) {
const imgUrl = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'); // 获取生成的图片的url
console.log(imgUrl)
window.location.href = imgUrl; // 下载图片
});