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>
相关推荐
kyriewen15 分钟前
白宫前脚下了限制令,OpenAI 后脚就把 GPT-5.6 发了
前端·gpt·openai
用户40269244819081 小时前
CRMEB Pro 新增后台接口全链路:路由、权限、验证器、返回格式一次讲清
前端·后端
泉城老铁1 小时前
springboot+vue+ ffmpeg 实现视频的拉流播放
前端
PedroQue992 小时前
uni-router v1.8.0新增冷启动守卫补执行
前端·uni-app
xiaok2 小时前
部署之后,本地浏览器还在读取旧缓存导致页面一直显示loading中
前端
用户059540174462 小时前
Redis缓存一致性踩坑实录:线上故障排查6小时,我用pytest+内存快照把它永久关进了笼子
前端·css
星栈2 小时前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:第一版先把列表和详情跑通
前端·rust·前端框架
用户1733598075372 小时前
Vue 3 SPA 首屏优化:从 3s 到 1.2s 的 5 个实践
前端·vue.js
咖啡无伴侣2 小时前
基础骨架:30 分钟搭好 pnpm workspace,完成双项目 Monorepo 迁入
前端
谷无姜2 小时前
Webpack5 进阶思考:那些官方文档没讲清楚的事
前端·webpack