uniapp使用Canvas绘制海报代码示例微信小程序下载海报画布

uniapp使用Canvas绘制海报代码示例微信小程序下载海报画布

uni-app官网

示例:

<template>
  <view class="container">
	  <view>
		  <canvas canvas-id="myCanvas" class="canvas"></canvas>		  
	  </view>
	
	<view>
		  <button @tap="downloadPoster" class="download-btn">下载海报</button>
	</view>
	
  </view>
  
</template>

<script>
export default {
  onLoad() {
    this.drawPoster();
  },
  methods: {
  
	
	// 下载海报
	downloadPoster() {
	  // 获取 Canvas 绘制内容的临时图片文件路径
	  uni.canvasToTempFilePath({
		canvasId: 'myCanvas',
		success: (res) => {
		  // 将临时图片文件保存到相册
		  uni.saveImageToPhotosAlbum({
			filePath: res.tempFilePath,
			success: () => {
			  uni.showToast({
				title: '保存成功',
				icon: 'success'
			  });
			},
			fail: (err) => {
			  uni.showToast({
				title: '保存失败',
				icon: 'none'
			  });
			  console.error(err);
			}
		  });
		},
		fail: (err) => {
		  console.error(err);
		}
	  }, this);
	},
	  
    // 绘制海报
    drawPoster() {
      // 获取 Canvas 上下文
      const ctx = uni.createCanvasContext('myCanvas', this);
      
      // 加载背景图
      uni.getImageInfo({
        src: 'https://img-cdn-tx.dcloud.net.cn/uni-app/logo-U.png',
        success: (res) => {
          ctx.drawImage(res.path, 0, 0, 400, 600);
          
          // 加载头像图片
          uni.getImageInfo({
            src: 'https://img-cdn-tc.dcloud.net.cn/uploads/avatar/001/67/43/81_avatar_max.jpg?=1613651270',
            success: (res) => {
              ctx.drawImage(res.path, 50, 50, 80, 80);
              
              // 绘制姓名文字
              ctx.setFontSize(26);
              ctx.setFillStyle('#ff0000');
              ctx.fillText('Mike', 150, 100);
              
              // 加载小程序二维码图片
              uni.getImageInfo({
                src: 'https://img-cdn-tc.dcloud.net.cn/uploads/avatar/000/08/81/38_avatar_max.jpg?=0',
                success: (res) => {
                  ctx.drawImage(res.path, 50, 250, 80, 80);
                  
                  // 绘制完成,保存图片
                  ctx.draw(false, () => {
                    uni.canvasToTempFilePath({
                      canvasId: 'myCanvas',
                      success: (res) => {
                        console.log(res.tempFilePath);
                        // res.tempFilePath 就是绘制后的海报图片路径
                      }
                    }, this);
                  });
                }
              });
            }
          });
        }
      });
    }
  },
  
  
	
	
	
  
  
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.canvas {
  width: 300px;
  height: 400px;
}
</style>

结束

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值