13.电影选票功能如何实现?

使用canvas来实现选座功能

1. 实现思路

  1. canvas基础处理
  2. 座位绘制
  3. 交互添加
  4. 座位状态的管理状态,存储到哪里,数据结构设计

2. 具体实现

2.1 初始化 canvas

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1.0">
		<title></title>
		<style>
			canvas{
				border: 1px solid #000;
				display: block;
				margin: 0 auto;
			}
		</style>
	</head>
	<body>
		<canvas id="cinemaCanvas" width="800" height="600"></canvas>
		<script src="cinema.js"></script>
	</body>
</html>

2.2 绘制座位

const canvas = document.getElementById('cinemaCanvas')
const ctx = canvas.getContext('2d')

const rows = 10
const cols = 15
const seatSize = 40 //座位大小
const seatSpacing = 10 // 座位间隔
const seats = []

for (let row = 0; row < rows; row++) {
	const seatRow = []
	for (let col = 0: col < cols: col++) {
		seatRow.push({
			x: col * (seatSize + seatSpacing),
			y: row * (seatSize + seatSpacing),
			status: 'available'
		})
	}
	seats.push(seatRow)
}

function drawSeats() {
	seats.forEach(row => {
		row.forEach(seat => {
			ctx.fillStyle = getSeatColor(seat.status)
			ctx.fillReat(seat.x, seat.y, seatSize, seatSize)
		})
	})
}

function getSeatColor(status) {
	switch (status) {
		case 'available':
			return 'green'
		case 'selected':
			return 'blue'
		case 'unavailable':
			return 'red'
		default:
			return 'gray'
	}
}

drawSeats()

2.3 添加事件

如何获取到我们当前点击的是canvas的那个点?

canvas.addEventListener('click', (event) => {
	const rect = canvas.getBoundingClientRect()
	const x = event.clientX - rect.left
	const y = event.clientY - rect.top

	seats.forEach(row => {
		row.forEach((seat) => {
			if (x >= seat.x && x <= seat.x + seatSize && y >= seat.y && y <= seat.y + seatSize) {
				if(seat.status === 'available'){
					seat.status='selected'
				}else if(seat.status === 'selected'){
					seat.status='available'
				}
				drawSeats()
			}
		})
	})
})

2.4 管理座位状态

for (let row = 0; row < rows; row++) {
	const seatRow = []
	for (let col = 0; col < cols; col++) {
		const status=Math.random()>0.8?'unavailable':'available'
		seatRow.push({
			x: col * (seatSize + seatSpacing),
			y: row * (seatSize + seatSpacing),
			status: status
		})
	}
	seats.push(seatRow)
}

优化

  • 优化鼠标移入移除