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>
相关推荐
小小码农Come on7 分钟前
QPainter双缓冲区实现一个简单画图软件
linux·服务器·前端
nunumaymax9 分钟前
【第三章-react 应用(基于 react 脚手架)】
前端·react.js·前端框架
空中海11 分钟前
第一章:Vue 基础与模板语法
前端·javascript·vue.js
mCell16 分钟前
为什么我不建议初学者一上来就用框架学 Agent
javascript·langchain·agent
每天吃饭的羊25 分钟前
水平,垂直居中
前端·javascript·html
鼎道开发者联盟1 小时前
鼎享会 | OpenClaw Control UI 前端架构全解析:自研 UI 对接 Server 实操指南
前端·ui·架构·openclaw·control ui
尘世中一位迷途小书童1 小时前
一套完整的给予ceium封装的组件库,可满足企业级开发
前端
Z_Wonderful1 小时前
微前端:Webpack 配置 vs Vite 配置 超清晰对比
前端·webpack·node.js
thankseveryday1 小时前
Three.js 把 Blender 绘制的曲线(Bezier / 曲线) 导入 Three.js 并作为运动路径 / 动画路径使用
开发语言·javascript·blender