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>
相关推荐
再玉米地里吃过亏32 分钟前
ONENET平台API鉴权错误
前端
网络点点滴34 分钟前
Vue3中Suspense的使用
前端·javascript·vue.js
饼干哥哥1 小时前
搭建一个云端Skills系统,随时随地记录TikTok爆款
前端·后端
酉鬼女又兒1 小时前
零基础快速入门前端Web存储(sessionStorage & localStorage)知识点详解与蓝桥杯考点应用(可用于备赛蓝桥杯Web应用开发)
开发语言·前端·javascript·职场和发展·蓝桥杯·html
DanCheOo1 小时前
# 从"会用 AI"到"架构 AI":高级前端的认知升级
前端·ai编程
社恐的下水道蟑螂1 小时前
前端面试必问 Git 通关指南:常用命令速查 + merge/rebase 深度辨析,看完再也不慌
前端·git·面试
angerdream2 小时前
最新版vue3+TypeScript开发入门到实战教程之组件通信之二
javascript·vue.js
小只笨笨狗~2 小时前
解决objectSpanMethod与expand共存时展开后表格错位问题
开发语言·javascript·ecmascript
None3212 小时前
NestJS 流式文件上传实践:从 Multer 到 Busboy 的进阶之路
前端·后端
海浪浪2 小时前
Symbol 产生的背景以及应用场景
前端·javascript