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>
相关推荐
rising start几秒前
二、Vue3 核心基础:API 对比、Setup 与响应式详解
前端·javascript·vue.js
meilindehuzi_a6 分钟前
撕开 JS 的 Class 面具:从构造函数的 new 降生到顶层原型链的终极通关
开发语言·javascript·ecmascript
ofoxcoding24 分钟前
MiniMax M3 实测手记:踩完坑之后,我总结了报错处理和省 token 的几个办法
java·前端·人工智能·ai
阿坨30 分钟前
JavaScript异步编程:Promise与async/await
javascript
YG亲测源码屋31 分钟前
html表白代码大全可复制免费 html表白网页制作源码
前端·html
夜雪闻竹34 分钟前
React Query + REST API 最佳实践
前端·react.js·前端框架
段ヤシ.35 分钟前
回顾Java知识点,面试题汇总Day12:tomcat、 Java Web(持续更新)
java·前端·tomcat·java web
JAVA学习通37 分钟前
从 Bean 到微服务:一张图吃透 Spring 全家桶底层原理
java·前端·spring
古韵38 分钟前
前端请求库的下一个进化方向:从 Promise 到策略化
前端
独特的螺狮粉40 分钟前
蛋鸡养护周期管理系统 - 鸿蒙PC Electron框架完整实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙