生成海报
好久没写博客,被这个h5保存下载困了有点久,记录一下
绘制画布
var ctx = uni.createCanvasContext('myCanvas', this);
ctx.setFillStyle('#fff'); // 默认白色
ctx.fillRect(0, 0, this.canvasW, this.canvasH) // fillRect(x,y,宽度,高度)
ctx.drawImage(this.posterBg, 0, 0, this.canvasW, this.canvasH) // drawImage(图片路径,x,y,绘制图像的宽度,绘制图像的高度)
ctx.setFontSize(12); // setFontSize() 设置字体字号
ctx.setFillStyle('#d0abab'); // setFillStyle() 设置字体颜色
let _strHeight = this.canvasH - 20; //绘制字体距离canvas顶部的初始高度
ctx.fillText('商城Id: ' + this.currId, 100, _strHeight);
ctx.draw(true,(ret)=>{ // draw方法 把以上内容画到 canvas 中。
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
destWidth: this.canvasW * 2, //分享图片尺寸=画布尺寸1*缩放比0.5*像素比2
destHeight: this.canvasH * 2,
quality: 1,
x: 0,
y: 0,
fileType: 'png',
success: (res) => {
this.posterUrl = res.tempFilePath; // 生成海报的暂存路径(base64)
}
})
});
图片跨域
我们拿远程的图片会跨域,解决办法就是转成本地图片。然后生成画布。
画布转图片base64后又上传获得远程路径(吐了)
uni.downloadFile({
url: '', // 远程图片
success: res => {
this.posterBg = res.tempFilePath;
}
})
h5下载
都推荐用a标签去下载,但是会打开一个新的页面,然后才能保存。不兼容ios
const tempLink = document.createElement("a");
tempLink.style.display = "none";
tempLink.href = this.posterUrl;
tempLink.setAttribute("download", 'AOC注册海报');
tempLink.setAttribute("target", "_blank");
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink)
找了好多,安卓长按都能保存图片,但是ios不行。uniapp本身图片带有show-menu-by-longpress事件触发不了。api事件有保存到相册的,uni.saveImageToPhotosAlbum 又不兼容h5
经过多方测试发现,给图片套一层canvas可以触发,但是图片标签得是原生的img,如果写成uniapp里的image是不会生效的
<!-- 生成图片套了一层canvas -->
<canvas :style="{ width: canvasW + 'px', height: canvasH + 'px' }">
<img class="img-poster" :src="posterUrl" alt="">
</canvas>