一个分享WordPress、Zblog、Emlog、Typecho等主流博客的教程网站!
当前位置:网站首页 > 其他相关教程 > 正文

微信小程序canvas绘制渐变背景颜色方法

作者:xlnxin发布时间:2023-10-06分类:其他相关教程浏览:432


导读:<template><view class="mapp-container"><canvas ...
<template>
	<view class="mapp-container">		
		<canvas :style="{width: canvasWidth + 'px',height:canvasHeight + 'px'}" type="2d" canvas-id="myCanvas" id="myCanvas"></canvas>
	</view>
</template>
 
<script>
	export default {
 
		data() {
			return {
				canvasHeight: 0,
				canvasWidth: 0
			}
		},
		onLoad() {
			let {
				windowHeight,
				statusBarHeight
			} = uni.getSystemInfoSync();
			this.canvasHeight = windowHeight;
			this.canvasWidth = this.rpxToPx(750);
			setTimeout(()=>{
					this.init()
			},50)
		},
		methods: {
			init() {
				let canvasH = this.canvasHeight;
				let canvasW = this.canvasWidth;
				const query = wx.createSelectorQuery()
				query.select('#myCanvas')
					.fields({node: true,size: true})
					.exec((res) => {
					const canvas = res[0].node;
					const ctx = canvas.getContext('2d');
					const dpr = wx.getSystemInfoSync().pixelRatio
					canvas.width = res[0].width * dpr // 获取宽
					canvas.height = res[0].height * dpr // 获取高
					ctx.scale(dpr, dpr)
			
					// 绘制背景
					const grd = ctx.createLinearGradient(0, 0, 0, canvasH)
					grd.addColorStop(0, '#27D0FF')
					grd.addColorStop(0.5, '#ffffff')
					ctx.fillStyle = grd;
					ctx.fillRect(0, 0, canvasW, canvasH)
					
 
									
					
				})
			},
 
			// rpx转px
			rpxToPx(rpx) {
				const screenWidth = uni.getSystemInfoSync().screenWidth
				return (screenWidth * Number.parseInt(rpx)) / 750
			},
		}
	}
</script>


标签:程序小程序