网站开发junke100,江门建站软件,影视网站搭建哪个系统好,宁波seo软件1、将dom转换为图片 这里我们使用html2canvas工具插件先将dom转为canvas元素然后canvas拥有一个方法可以将绘制出来的图形转为url然后下载即可注意#xff1a;如果元素使用了渐变背景并透明的话#xff0c;生成的图片可能会有点问题。我下面这个案例使用了渐变背景实现元素对…1、将dom转换为图片 这里我们使用html2canvas工具插件先将dom转为canvas元素然后canvas拥有一个方法可以将绘制出来的图形转为url然后下载即可注意如果元素使用了渐变背景并透明的话生成的图片可能会有点问题。我下面这个案例使用了渐变背景实现元素对角线就有问题。 1.1、下载插件并导入
npm install --save html2canvasimport html2canvas from html2canvas;1.2、编写代码
templatediv classhomediv classcontent/divbutton clickcreatUrl下载图片/button/div
/templatescript
import html2canvas from html2canvas;export default {name: HomeView,components: {},methods: {// 生成图片creatUrl() {const setup {useCORS: true, // 使用跨域};const dom document.querySelector(.content)html2canvas(dom, setup).then((canvas) {// 将canvas 转换成图片地址const link canvas.toDataURL(image/jpg);this.downloadPicture(link, test.jpg);});},// 导出图片downloadPicture(link, name 未命名文件) {const file document.createElement(a);file.style.display none;file.href link;file.download decodeURI(name);document.body.appendChild(file);file.click();document.body.removeChild(file);}}
}
/scriptstyle langscss scoped
.home {.content {width: 100px;height: 100px;border: 1px solid #000;/* 元素添加对角线 */background: linear-gradient(to bottom left,white 50%,#000,white 51%);}
}
/style1.3、效果 2、将dom转为图片并放到pdf文件里进行下载 这里使用jspdf插件创建一个pdf文件并把上面生成的图片放入pdf中即可完成。上面将dom元素转为图片并生成url就不再讲解 2.1、下载插件并导入
// 下载
npm install jspdf --save
npm install --save html2canvas// 导入
import jsPDF from jspdf
import html2canvas from html2canvas;2.2、js代码
// 生成pdf
creatPdf() {const setup {useCORS: true, // 使用跨域};const dom document.querySelector(.content)html2canvas(dom, setup).then((canvas) {// 将canvas 转换成图片地址const link canvas.toDataURL(image/jpg);// 创建pdf文件const pdf new jsPDF();/** 1. 图片地址* 2. 格式化图片格式* 3. 图片在pdf中的x坐标* 4. 图片在pdf中的y坐标* 5. 图片在pdf中的宽度* 6. 图片在pdf中的高度*/pdf.addImage(link, JPEG, 0, 0, 210, 297); // 参数为下载的pdf的文件名pdf.save(test.pdf);});
},2.3、注意 我这里斜线是用背景渐变实现的有兴趣可以查看第三章CSS的第18篇文章注意如果有背景图的话生成出来的图片可能会有问题。