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>
相关推荐
程序员黑豆21 分钟前
从零开始:创建第一个鸿蒙应用程序
前端·harmonyos
只与明月听1 小时前
LangChain 学习-掌握LangChain Core API
前端·人工智能·后端
Listen·Rain1 小时前
Vue3中customRef详解
前端·javascript·vue.js
sugar__salt1 小时前
Document 切割:RAG 知识库数据预处理实战
javascript·langchain·embedding·js·rag·cheerio
小粉粉hhh1 小时前
React(三)——Redux
前端·javascript·react.js
易知微EasyV数据可视化2 小时前
定制化3D组件开发:打造差异化孪生体验
前端·人工智能·经验分享·数字孪生
多加点辣也没关系2 小时前
JavaScript|第24章:事件循环与并发模型
开发语言·javascript·ecmascript
前端炒粉3 小时前
Vue2 SSE 流式对话完整前端代码
前端·sse·流式输出
BIM云平台开发3 小时前
【App.vue里跟踪页面跳转和用户ID】
开发语言·前端·javascript
汪汪大队u3 小时前
Zabbix 6.0 部署踩坑记:从启动失败到 Web 成功访问
前端·zabbix