目录

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

目录

微信小程序canvas绘制渐变背景颜色,微信小程序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>