uni-app使用canvas适配手机宽高进行渲染

uni-app使用canvas适配手机宽高进行渲染

javascript 复制代码
<template>
	<view class="countStyle">
		<view class="bgimg" :style="{ 'background-image': 'url(' + imager + ')', 'height': bgHeight + 'px' }">
			<canvas canvas-id="firstCanvas" class="cansStyle" />
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	import config from '@/config';

	const imager = ref(config.config.baseUrl + '/wximages/menu/unloadWork.png');
	const canvasWidth = uni.getSystemInfoSync().windowWidth;
	const canvasHeight = uni.getSystemInfoSync().windowHeight;

	// 计算背景图片高度以保持等比缩放
	const bgImageAspectRatio = 450 / 600; // 背景图片的原始宽高比
	const bgHeight = canvasWidth / bgImageAspectRatio;

	const context = uni.createCanvasContext('firstCanvas');

	const points = [
		{ x: 100 * canvasWidth / 375, y: 100 * bgHeight / 667 },
		{ x: 150 * canvasWidth / 375, y: 100 * bgHeight / 667 },
		{ x: 150 * canvasWidth / 375, y: 150 * bgHeight / 667 },
		{ x: 50 * canvasWidth / 375, y: 150 * bgHeight / 667 },
	];

	onMounted(() => {
		drawPolyline();
	});

	function drawPolyline() {
		context.setStrokeStyle("#ffff00");
		context.setLineWidth(10);

		context.moveTo(points[0].x, points[0].y);

		for (let i = 1; i < points.length; i++) {
			context.lineTo(points[i].x, points[i].y);
		}

		context.stroke();
		context.draw();
	}
</script>

<style lang="scss" scoped>
	.countStyle {
		overflow: auto;
	}

	.bgimg {
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center;
		width: 100%;
	}

	.cansStyle {
		width: 100%;
		height: 100%;
	}
</style>
相关推荐
ZhengEnCi18 分钟前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
kyriewen1 小时前
我给 61 个前端库排了两次名,最多差了 46 位
前端·javascript·程序员
亲亲小宝宝鸭2 小时前
Cesium启动:TLE数据是如何变成轨迹线的
前端·cesium
阿里云云原生2 小时前
对话即构建,在 AgentCore 构建 Agent 就是这么简单
前端·agent
夕水3 小时前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript
KevinWang_3 小时前
iOS 开发计划(五) - 做一个离线音乐播放器
javascript
狗头大军之江苏分军3 小时前
前端转行干能干什么?我转行试了下(被迫)
前端·后端
孟陬3 小时前
Foobar 技术周刊#2:约会已死?用户急剧下滑,约会App大概率会弱化约会属性转向轻陪伴。我有个建议:
前端·后端·rust
parade岁月4 小时前
VTable Guild 3.0.0 发布,面向 Vue 3 的 ProTable 式业务表格
前端
xurileidian5 小时前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python