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>
相关推荐
pythonpioneer6 分钟前
【2025】Solid Edge下载安装教程(附安装包)保姆级安装步骤
前端·数据库·其他·edge
岁月宁静23 分钟前
图像生成接口的工程化设计与落地实践:封装豆包图像生成模型 Seedream 4.0 API
前端·人工智能·node.js
前端伪大叔25 分钟前
第26篇:爆赚利器!三步搞定 Freqtrade 核心买卖信号,手把手教你写自动交易策略!
javascript·mysql·微信
谢尔登36 分钟前
【GitLab/CD】前端 CD
前端·gitlab
ruanCat38 分钟前
在使用 changeset 时,如何在更新底部依赖时,触发上层依赖更新
前端·github
wendao38 分钟前
我开发了个极简的LLM提供商编辑器
前端·react.js·llm
小白学鸿蒙39 分钟前
新手记录使用uniapp-x开发鸿蒙应用
华为·uni-app·harmonyos
烟袅42 分钟前
从一行代码说起:深入理解 JavaScript 中的字符串类型与模板字符串
前端·javascript·代码规范
慢知行1 小时前
从 0 到 1 搭建 Vite+Vue3+TS 工程模板:能上手操作的指南
前端·vue.js·typescript
咖啡の猫1 小时前
Vue解决开发环境 Ajax 跨域问题
前端·vue.js·ajax