【uniapp H5】海报生成及下载

这里写自定义目录标题

生成海报

好久没写博客,被这个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
uni.saveImageToPhotosAlbum 兼容
经过多方测试发现,给图片套一层canvas可以触发,但是图片标签得是原生的img,如果写成uniapp里的image是不会生效的

<!-- 生成图片套了一层canvas -->
<canvas :style="{ width: canvasW + 'px', height: canvasH + 'px' }">
	<img class="img-poster" :src="posterUrl" alt="">
</canvas>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值