uni-app: canvas-draw graphics 4 (get the width and height of the canvas, and draw graphics according to the width and height of the canvas)

Effect

code

var width = '';
var height = ''; 
const query = uni.createSelectorQuery();
//Get the width
query.select('#firstCanvas').fields({     size: true  }, (res) => {      width = res.width;      height = res.height; }).exec();  console.log('width'+width);  console.log('height'+height);






<template>
	<view>
		<!-- 创建了一个宽度为300像素,高度为200像素的canvas元素。canvas-id属性被设置为"firstCanvas",可以用来在JavaScript中获取该canvas元素的上下文对象。 -->
		<canvas style="width:200px; height:300px; border: 1px solid black;" canvas-id="firstCanvas"
			id="firstCanvas"></canvas>
	</view>
</template>
<script>
	export default {
		onReady: function(e) {
			//创建一个画布上下文对象,用于进行绘图操作。'firstCanvas'是一个指定的画布标识符,表示在页面上的哪个 <canvas> 元素上进行绘制。
			var context = uni.createCanvasContext('firstCanvas')
			var width = '';
			var height = ''; 
			const query = uni.createSelectorQuery();
			//获取宽度
			query.select('#firstCanvas').fields({
				size: true
			}, (res) => {
				width = res.width;
				height = res.height;
			}).exec();
			console.log('宽度'+width);
			console.log('高度'+height);
			//绘制路径中的线条。
			context.setStrokeStyle("#aaaaff")
			// 设置线条的宽度为2个像素。
			context.setLineWidth(2)
			// 绘制横线
			context.beginPath(); // 开始路径绘制
			context.moveTo(width/2, 0); // 将起点移动到 (0, 100)
			context.lineTo(width/2, 50);
			context.stroke(); // 绘制线条
			var x1 = width/4; // 第一个竖线的起点 x 坐标
			var y1 = 50; // 第一个竖线的起点 y 坐标
			var y2 = 30; // 短竖线的高度
			var horizontalLength = width/2; // 横线的长度
			context.beginPath();
			context.moveTo(x1, y1 + y2); // 移动到第一个短竖线的起点
			context.lineTo(x1, y1); // 绘制第一个短竖线
			context.moveTo(x1 + horizontalLength, y1 + y2); // 移动到横线的右端下方
			context.lineTo(x1 + horizontalLength, y1); // 绘制第二个短竖线
			context.moveTo(x1, y1); // 移动到横线的左端下方
			context.lineTo(x1 + horizontalLength, y1); // 绘制横线/*  */
			context.stroke(); // 绘制线条
			// 将之前的绘图操作渲染到画布上。
			context.draw()
		},
		methods: {}
	}
</script>

Here, because I set the border border: 1px solid black on the canvas, the width and height must be increased by 1px+1px=2px pixel values ​​respectively.

Guess you like

Origin blog.csdn.net/weixin_46001736/article/details/133345514