canvas 使用transform 实现不同屏幕尺寸的适配

实现原理是使用设计稿尺寸和现屏幕的比例使用transform进行缩放

canvas 使用transform 实现不同屏幕尺寸的适配

<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title></title>
	</head>
	<body>
		<style>
			* {
				margin: 0;
				padding: 0;
			}

			.box {
				width: 100vw;
				height: 100vh;
				background-image: url('./img/3.png');
				background-size: 100% 100%;
				background-repeat: no-repeat;
				position: relative;
			}

			#canvas {
				position: absolute;
				z-index: 10;
			}

			.tips {
				position: absolute;
				z-index: 10;
				color: red;
				width: 100px;
				height: 50px;
				left: 50.7vw;
				top: 21.8vw;
				border: 3px solid red;
				text-align: center;
				line-height: 50px;
				background-color: rgba(255, 255, 255, 0.3);
			}
		</style>
		<div class="box">
			<div class="tips">椅子</div>
			<canvas id="canvas"></canvas>
		</div>
		<script>
			const canvas = document.getElementById('canvas');
			console.log(window.innerWidth, window.innerHeight)
			const width = window.innerWidth;
			const height = window.innerHeight;
			canvas.width = width;
			canvas.height = height;
			
			let context = canvas.getContext("2d");
			let x = width/1920;
			let y = height/1080;
		
			context.transform(x,0,0,y,0,0)
			context.strokeStyle = "red";
			context.lineWidth = 3;
			context.moveTo(880, 450);
			context.lineTo(975, 450);

			context.save(); //可以临时保存,后面可以设置别的线宽和颜色
			context.stroke();
			
			context.moveTo(1900,0)
			context.lineTo(1900,10);
			context.stroke();
			
		</script>
	</body>
</html>

上一篇:base64照片压缩


下一篇:最新生成canvas实例并且作用于等比例压缩图片上传或者绘制海报