uni-app使用canvas生成图片并保存到相册

<template>
	<view>
		<canvas canvas-id="myCanvas" v-if="show"></canvas>
		<button type="default" @click="seave" v-if="!show">点击</button>
		<button type="default" @click="myimg" v-if="show">保存</button>
	</view>

</template>

<script>
	export default {
		data() {
			return {
				show:false,
				imgs:'../../static/logo.png',
				text:'文字'
			}
		},
		onLoad() {},
		methods: {
			seave(){
				let _this = this
				_this.show = true
				const ctx = uni.createCanvasContext('myCanvas')
				ctx.fillText('Hello', 20, 20)//描绘文本
				ctx.fillText(_this.text, 50, 20)
				ctx.drawImage(_this.imgs,50,50)//描绘图片
				
				ctx.draw(false, (() => {
					setTimeout(()=>{
						uni.canvasToTempFilePath({
							canvasId: 'myCanvas',
							destWidth: _this.cropW*_this.canvasScale*2, //分享图片尺寸=画布尺寸1*缩放比0.5*像素比2
							destHeight: _this.cropH*_this.canvasScale*2,
							quality:1,
							fileType:'jpg',
							success: (res) => {
								// console.log(res,'success')
								uni.compressImage({
									src: res.tempFilePath,
									quality: 100,
									success: res => {
										const share_img=res.tempFilePath
										uni.canvasToTempFilePath({
											canvasId: 'myCanvas',
											destWidth: _this.cropW*2,   //展示图片尺寸=画布尺寸1*像素比2
											destHeight: _this.cropH*2,
											quality:1,
											fileType:'jpg',
											success: (res) => {
												console.log(res.tempFilePath);
												uni.setStorageSync('imgs',res.tempFilePath)
												uni.hideLoading()
												const img = res.tempFilePath
												// _this.show = false
												_this.$emit('confirm', {
													share_img,
													img
												})
											},
										}, _this);
									}
								})
							},
						}, _this);
					},500)
				})())
			},
			
			myimg(){
				uni.saveImageToPhotosAlbum({
					filePath: uni.getStorageSync('imgs'),
					success: function() {
						uni.showToast({
							icon: 'none',
							position: 'bottom',
							title: "图片已下载至【图库】,请打开【图库】查看", // res.tempFilePath
						});
					}
				});
			}
		}
	}
</script>

<style>

</style>


  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值