h5不能通过微信调用下载方法,a标签也不支持,所以通过微信本身的长按 弹出下载,但是在有些应用时 我们是希望将页面合成一张图,然后进行下载,本人摸坑许久,实现如下
需要合成的dom节点
<view id="main_content"> 内容 </view>
合成图片后赋值链接的img
<image class="downImgSty" :src="testUrl" :style="{height:imgH+'px'}" mode=""></image>
合成图片插件 html2canvas
import html2canvas from 'html2canvas';
进入页面时 执行合成函数creatImg
creatImg() {
const $this = this;
this.imgH=document.getElementById("main_content").offsetHeight;
const dom = document.querySelector("#main_content");
const box = window.getComputedStyle(dom);
// DOM 节点计算后宽高
const width = this.parseValue(box.width);
const height = this.parseValue(box.height);
// 获取像素比
const scaleBy = this.DPR();
// 创建自定义 canvas 元素
var canvas = document.createElement('canvas');
// 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
canvas.width = width * scaleBy;
canvas.height = height * scaleBy;
// 设定 canvas css宽高为 DOM 节点宽高
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
let x = width;
let y = height;
html2canvas(dom, {canvas,
dpi: 350,
}).then(function () {
$this.testUrl=canvas.toDataURL("image/png"); //生成的图片链接
uni.hideLoading();
})
},
parseValue(value) {
return parseInt(value, 10);
},
DPR() {
if (window.devicePixelRatio && window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
return 1;
}
图片的生成略带一点点模糊,我是没招了
图片的放置
微信的长按操作 是当前元素,那么我们要使得长按的是生成的图片,这样才能保住下载时下载的是目标图片,有两种方法
1 图片生成完成后隐藏 main_content 只显示合成的图片
2 通过定位 将目标image 的层级放置在main_content 之上,这样长按 按到的对象就是image,就能愉快的保存了
position: absolute;
top: 0;
opacity: 0;
z-index: 999;