赞
踩
1.下载引入html2canvas
npm i html2canvas -save
- //printCharts.vue
- import html2canvas from "html2canvas";
2.点击按钮下载图片
- <button @click="printBtn('.toImg2')"></button>
- <div class="toImg2"></div>
- // printCharts.vue
- async printBtn(img) {
- const card = document.querySelector(img); //img 为要下载图片的dom元素
- const canvas = await html2canvas(
- card,
- {
- width: 795, //设置canvas的宽度
- height: 420, //设置canvas的高度
- useCORS: true, // 【重要】开启跨域配置
- allowTaint: true, // 允许跨域图片
- }
- ) // 创建一个临时的a标签
- let a = document.createElement("a");
- document.body.appendChild(a);
-
- // 为a标签添加属性
- a.setAttribute("href", canvas.toDataURL("image/jpg", 1.0)); //toDataUrl:将canvas画布信息转化为base64格式图片
- a.setAttribute("download", "text.png"); //导出图片名称
- a.setAttribute("target", "_self"); // 在当前窗口中打开
- a.click(); // 同时调用a标签的点击事件
-
- // 最后删除该临时节点
- document.body.removeChild(a);
- },
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。