vue整合html2canvas插件将div生成图片并下载到本地

1、安装html2canvas插件

npm install html2canvas --save

2、需要使用的页面引入html2canvas组件

import html2canvas from 'html2canvas'

3、主要实现代码

//里面放置你需要生成图片的内容
//方法 exportPic(){ let self = this; event.preventDefault(); let canvas2 = document.createElement("canvas"); let _canvas = document.getElementById("canvasPic"); let w = parseInt(window.getComputedStyle(_canvas).width); let h = parseInt(window.getComputedStyle(_canvas).height); //放大canvas画布,然后放在较小的容器内,像素会升高 canvas2.width = w*2; canvas2.height = h*2; canvas2.style.width = w+"px"; canvas2.style.height = h+"px"; let context = canvas2.getContext("2d"); context.scale(2,2); html2canvas(document.getElementById('canvasPic'),{ canvas:canvas2 }).then(function (canvas) { let fileName = "图片名字" + ".jpg" let imgUri = canvas.toDataURL("image/jpeg",2); // 获取生成的图片的url // console.log(imgUri) //下载方法 self.fileDown(imgUri,fileName); }); }, fileDown(url, name) { let self = this let fileName = name self.axios({ method: "post", url: url, responseType: "blob", }).then(data => { let blob = new Blob([data.data], { type: "application/json" }); if (window.navigator.msSaveOrOpenBlob) { //msSaveOrOpenBlob方法返回bool值 navigator.msSaveBlob(blob); //本地保存 } else { let link = document.createElement("a"); //a标签下载 link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); window.URL.revokeObjectURL(link.href); } }); },

4、申明:

              本文修改自:https://blog.csdn.net/weixin_43876684/article/details/86322682

 

你可能感兴趣的:(vue整合html2canvas插件将div生成图片并下载到本地)