使用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>
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()
如何获取到我们当前点击的是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()
}
})
})
})
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)
}