uniapp 画布canvas的用法

效果图:
在这里插入图片描述
代码:

<template>
	<view class="demo">
		<canvas :style="{ width: canvasW + 'px', height: canvasH + 'px' }" canvas-id="myCanvas" id="myCanvas01"> </canvas>
		<button class="btn" type="primary" v-if="isShow" @click="saveImage">保存图片到相册</button>
	</view>
</template>
<script>
	export default {		
		data() {
			return {
				canvasW:0, // 画布宽
				canvasH:0, // 画布高
				SystemInfo:{}, // 设备信息
				goodsImg: {}, // 商品主图信息
				ewmImg:{}, // 二维码图片信息
				ewmW:120, // 二维码大小
				title:'Apple/苹果 iPhone 11全新正品国行全网通4G智能手机苹果SE2', // 商品标题
				price:'4158.00', // 价格
				Oldprice:'4999.00', // 原价
				name:'浪迹天涯', // 推荐人
				isShow:false ,
			}
		},
		async onLoad() {
			// 获取设备信息,主要获取宽度,赋值给canvasW 也就是宽度:100%
			this.SystemInfo = await this.getSystemInfo();
			
			// 获取商品主图,二维码信息,APP端会返回图片的本地路径(H5端只能返回原路径)
			let goodsImgUrl = '/static/bjt.jpg'  // 主图本地路径,也可以用网络地址
			let ewmImgUrl = '/static/2wm.jpg'  
			this.goodsImg = await this.getImageInfo(goodsImgUrl);
			this.ewmImg = await this.getImageInfo(ewmImgUrl);

			this.canvasW = this.SystemInfo.windowWidth; // 画布宽度
			this.canvasH = this.SystemInfo.windowHeight - 60; //this.goodsImg.height + this.ewmW + 10;  // 画布高度 = 主图高度+二维码高度 + 文字图片的间距(大概50)
			
			// 如果主图,二维码图片,设备信息都获取成功,开始绘制海报,这里需要用setTimeout延时绘制,否则可能会出现图片不显示。
			if(this.goodsImg.errMsg == 'getImageInfo:ok' && this.ewmImg.errMsg == 'getImageInfo:ok' && this.SystemInfo.errMsg == 'getSystemInfo:ok'){
				console.log('读取图片信息成功')
				uni.showToast({
					icon:'loading',
					mask:true,
					duration:10000,
					title: '海报绘制中',
				});
				setTimeout(()=>{
					var ctx = uni.createCanvasContext('myCanvas', this);
					// 1.填充背景色,白色
					ctx.setFillStyle('#fff'); // 默认白色
					ctx.fillRect(0, 0, this.canvasW, this.canvasH) // fillRect(x,y,宽度,高度)
					
					// 2.绘制商品主图,二维码
					ctx.drawImage(goodsImgUrl, 0, 0, this.canvasW, this.canvasW) // drawImage(图片路径,x,y,绘制图像的宽度,绘制图像的高度)
					ctx.drawImage(ewmImgUrl, this.canvasW-130, this.canvasW+10, this.ewmW, this.ewmW) // drawImage(图片路径,x,y,绘制图像的宽度,绘制图像的高度,二维码的宽,高)
					
					// 3.绘制商品标题,多余文字自动换行
					ctx.setFontSize(16); // setFontSize() 设置字体字号
					ctx.setFillStyle('#333'); // setFillStyle() 设置字体颜色
					
					/* str 这段代码是我百度找的,参考别人的。canvas不能自动换行,需要自行计算 */
					let _strlineW = 0;
					let _strLastIndex = 0; //每次开始截取的字符串的索引
					let _strHeight = this.canvasW +30; //绘制字体距离canvas顶部的初始高度
					let _num = 1;
					for (let i = 0; i < this.title.length; i++) {
						_strlineW += ctx.measureText(this.title[i]).width;
						if (_strlineW > this.canvasW-155) {
							if(_num == 2 && 2){
								//文字换行数量大于二进行省略号处理
								ctx.fillText(this.title.substring(_strLastIndex, i-5)+'...', 10, _strHeight);
								_strlineW = 0;
								_strLastIndex = i;
								_num++;
								break;
							}else{
								ctx.fillText(this.title.substring(_strLastIndex, i), 10, _strHeight);
								_strlineW = 0;
								_strHeight += 20;
								_strLastIndex = i;
								_num++;
							}
						}else if (i == this.title.length - 1) {
							ctx.fillText(this.title.substring(_strLastIndex, i + 1), 10, _strHeight);
							_strlineW = 0;
						}
					}
					
					
					// 4、商品价格
					ctx.setFontSize(16) // 字号
					ctx.setFillStyle('#e31d1a') // 颜色
					ctx.fillText('¥'+this.price, 10, this.canvasW +75); // (文字,x,y)
					ctx.setFontSize(12)
					ctx.setFillStyle('#b8b8b8')
					ctx.fillText('原价¥'+this.Oldprice, 100, this.canvasW +75);
					
					// 5、邀请信息
					ctx.setFontSize(16)
					ctx.setFillStyle('#333')
					ctx.fillText(this.name+'推荐给你', 10, this.canvasW +100);
					
					ctx.setFontSize(14)
					ctx.setFillStyle('#b8b8b8')
					ctx.fillText('长按或扫描识别二维码', 10, this.canvasW +this.ewmW);

					// draw方法 把以上内容画到 canvas 中
					ctx.draw(true,(ret)=>{						 
						this.isShow = true  // 显示按钮-保存图片到相册
						uni.showToast({
							icon:'success',
							mask:true,
							title: '绘制完成',
						});
						uni.canvasToTempFilePath({ // 保存canvas为图片
							canvasId: 'myCanvas',
							quality: 1,
							complete: function(res) {
								// 在H5平台下,tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败,APP端正常输出临时路径
								console.log(res.tempFilePath)								
								uni.setStorageSync('filePath',res.tempFilePath)  //保存临时文件路径到缓存
							} ,
						})
					});
				},1500)
				
			} else {
				console.log('读取图片信息失败')
			}
		},
		
		methods: {
			// 获取图片信息
			getImageInfo(image) {
				return new Promise((req, rej) => {
					uni.getImageInfo({
						src: image,
						success: function(res) {
							req(res)
						},
					});
				})
			},
			
			// 获取设备信息
			getSystemInfo(){
				return new Promise((req, rej) => {
					uni.getSystemInfo({
					    success: function (res) {
					        req(res)
					    }
					});
				})
			},
			
			// 保存图片到相册
			saveImage() {
				let filePath = uni.getStorageSync('filePath')	//从缓存中读取临时文件路径			
				wx.saveImageToPhotosAlbum({
					filePath: filePath,
					success(res) {
						uni.showToast({
							icon:'success',
							mask:true,
							title: '保存到相册了',
						});
					},
					fail(res) {
						console.log(res.errMsg)
					}
				})
			}
			
		}
	}
</script>

<style>
	.btn{
		margin-left: 10px;
		margin-right: 10px;
		margin-bottom: 10px;
		width: 94%;
	}
	
</style>


使用网络图片与本地图片的区别,详见红色标注。
在这里插入图片描述

参考了这篇文章:https://blog.csdn.net/qq_40745143/article/details/109313719

  • 17
    点赞
  • 81
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
uniapp中使用canvas绘制水印,可以通过以下步骤实现: 1. 首先,在uniapp项目中创建一个新的页面或组件,用于显示canvas画布。 2. 在该页面或组件中,使用`<canvas>`标签创建一个画布元素,并设置其宽度和高度。 3. 使用`uni.createCanvasContext()`方法创建一个绘图上下文对象,用于操作画布。 4. 使用绘图上下文对象的相关方法,如`fillText()`、`fillRect()`等来绘制水印内容。 5. 通过调用绘图上下文对象的`draw()`方法将绘制的内容显示在画布上。 下面是一个简单的示例代码,演示了如何在uniapp中使用canvas绘制水印: ``` <template> <view> <canvas id="canvas" style="width: 300px; height: 200px;"></canvas> </view> </template> <script> export default { onReady() { const ctx = uni.createCanvasContext('canvas', this); ctx.setFillStyle('rgba(0, 0, 0, 0.5)'); // 设置水印颜色和透明度 ctx.setFontSize(16); // 设置水印字体大小 ctx.fillText('水印内容', 10, 20); // 绘制水印文本 ctx.draw(); // 绘制到画布上 } } </script> ``` 在上述代码中,我们使用了uniapp提供的`uni.createCanvasContext()`方法创建了一个绘图上下文对象,并通过该对象的`setFillStyle()`、`setFontSize()`以及`fillText()`方法来设置水印的样式和内容。最后,通过调用`draw()`方法将绘制的水印显示在画布上。 需要注意的是,在uniapp中使用canvas绘制水印时,需要确保在`onReady()`生命周期函数中进行绘制操作,以确保画布已经完全加载。另外,还需要注意设置画布的宽度和高度,以及调整水印的位置和样式,以满足具体需求。 希望以上内容对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值