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>
相关推荐
hunterandroid4 分钟前
[鸿蒙从零到一] HarmonyOS 分布式能力与设备协同实战:从发现设备到任务闭环
前端
lichenyang45319 分钟前
从图片创作到本地可复现的 AIGC 全栈闭环:AIGC Creative Studio 实践复盘
前端·后端
牧艺26 分钟前
别急着 Vibe Coding:AI 三小时写完需求后,我为什么宁愿多花一天
前端·agent·vibecoding
java1234_小锋28 分钟前
Vue3+Vite简介以及构建第一个HelloWorld实例
前端·javascript·vue.js·vite
前进的搬砖er29 分钟前
1.cesium 的基础知识篇
前端
计算机魔术师33 分钟前
在 M1 Max 上运行 2.8T 参数的 Kimi K3:Deltafin 项目实现 0.0687 token/s 推理
前端
黄林晴34 分钟前
你敢信吗?同样是跨端,KMP 跟 RN 居然差这么多!
android·前端
windliang36 分钟前
Claude Code 源码分析(四):Tool 工具系统-从 Schema 到真实执行
前端·ai编程·claude
10WTW011 小时前
Sprite-Motion-Lab:雪碧图动画编辑器
前端·css·雪碧图·spritemotionlab·10wtw01
夏天要喝冰可乐1 小时前
用 Gitee Go 搭建WorkBuddy云端定时任务
前端·ai编程