最近做H5项目用html2canvas来截取保存当前页面的功能,然后在最新的ios版本的手机上一切正常,然而在ios10以下版本的手机拿不到截取的图片。
html2canvas(this.$refs.imageWrapper, { backgroundColor: null // 解决生成的图片有白边 }).then(canvas => { let dataURL = canvas.toDataURL("image/png"); let storeAs = "writing" + "/" + this.timeName() + "/" + this.getUuid() + "." + "png"; this.imgFile = this.getBase64Img(dataURL); }); getBase64Img: function(file) { let fileName = "writing.png"; //图片名称 var arr = file.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], fileName, { type: mime }); }this.imgFile = this.getBase64Img(dataURL); ios10以下结果为空,拿不到图片url。 所以根据低版本ios做了单独兼容性方法:
html2canvas(this.$refs.imageWrapper, { backgroundColor: null // 解决生成的图片有白边 }).then(canvas => { let dataURL = canvas.toDataURL("image/png"); let storeAs = "writing" + "/" + this.timeName() + "/" + this.getUuid() + "." + "png"; if(this.ios > 9){ this.imgFile = this.getBase64Img(dataURL); }else{ //低版本执行方法 let bold = this.getBase64Img(dataURL); let file = this.blobToFile(bold, "fileName"); } }); getBase64Img: function(file) { let fileName = "writing.png"; //图片名称 var arr = file.split(","), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } if(this.ios > 9){ return new File([u8arr], fileName, { type: mime }); }else{ //低版本执行方法 return new Blob([u8arr], { type: mime }); } }, //Blob方式获取图片方法 blobToFile: function(Blob, fileName) { Blob.lastModifiedDate = new Date(); Blob.name = fileName; return Blob; }, //获取ios版本方法 isIos() { var str= navigator.userAgent.toLowerCase(); var ver=str.match(/cpu iphone os (.*?) like mac os/); if(ver){ let num = ver[1].replace(/_/g,".").split(".")[0] //console.log("你当前的Ios系统版本为:",num); this.ios = num } }判断一下ios版本,在根据高低版本进行不同方法执行就解决了。