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>
相关推荐
bitbitDown2 分钟前
重构缓存时踩的坑:注释了三行没用的代码却导致白屏
前端·javascript·vue.js
xiaopengbc6 分钟前
火狐(Mozilla Firefox)浏览器离线安装包下载
前端·javascript·firefox
用户0165238444127 分钟前
Webpack5 入门与实战,前端开发必备技能无密
前端
小高00727 分钟前
🔥🔥🔥前端性能优化实战手册:从网络到运行时,一套可复制落地的清单
前端·javascript·面试
古夕29 分钟前
my-first-ai-web_问题记录01:Next.js的App Router架构下的布局(Layout)使用
前端·javascript·react.js
Solon阿杰32 分钟前
solon-flow基于bpmnJs的流程设计器
javascript·bpmn-js
Solon阿杰33 分钟前
前端(react/vue)实现全景图片(360°)查看器
javascript·vue.js
杨超越luckly35 分钟前
HTML应用指南:利用POST请求获取上海黄金交易所金价数据
前端·信息可视化·金融·html·黄金价格
郝学胜-神的一滴36 分钟前
Three.js 材质系统深度解析
javascript·3d·游戏引擎·webgl·材质
Jerry40 分钟前
Compose 中的基本布局
前端