在HTML5的画布(Canvas)上添加多个球并在点击时响应,涉及到前端开发中的图形绘制和事件处理。以下是详细的基础概念、优势、类型、应用场景以及解决方案。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Balls</title>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script src="script.js"></script>
</body>
</html>
class Ball {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let balls = [];
const numBalls = 10;
for (let i = 0; i < numBalls; i++) {
const radius = 20;
const x = Math.random() * (canvas.width - radius * 2) + radius;
const y = Math.random() * (canvas.height - radius * 2) + radius;
const color = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
balls.push(new Ball(x, y, radius, color));
}
function drawBalls() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(ball => ball.draw(ctx));
}
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
balls.forEach(ball => {
const dx = mouseX - ball.x;
const dy = mouseY - ball.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < ball.radius) {
ball.color = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
}
});
drawBalls();
});
drawBalls();
drawBalls
函数清除画布并重新绘制所有球。requestAnimationFrame
来改善性能。通过以上步骤和代码示例,可以在画布上成功添加多个球并在点击时响应。
领取专属 10元无门槛券
手把手带您无忧上云