-_-#【Canvas】回弹

时间:2023-03-09 18:31:24
-_-#【Canvas】回弹

-_-#【Canvas】回弹

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="canvas" width="400" height="400" style="background:gray;"></canvas>
<script>
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d') function Ball(x, y, dx, dy, radius, color) {
this.x = x
this.y = y
this.dx = dx
this.dy = dy
this.radius = radius
this.color = color
} var balls = []
balls.push(new Ball(11, 111, 10, 5, 10, 'black'))
balls.push(new Ball(31, 11, 5, 5, 10, 'green'))
balls.push(new Ball(61, 41, 10, 5, 10, 'red'))
function move() {
context.clearRect(0, 0, canvas.width, canvas.height)
balls.forEach(function(ball) {
context.beginPath()
ball.x += ball.dx
ball.y += ball.dy
if (ball.x < ball.radius || ball.x > canvas.width - ball.radius) {
ball.dx = -ball.dx
}
if (ball.y < ball.radius || ball.y > canvas.height - ball.radius) {
ball.dy = -ball.dy
}
context.fillStyle = ball.color
context.strokeStyle = ball.color
context.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, false)
context.stroke()
context.fill()
})
window.requestAnimationFrame(move)
} window.requestAnimationFrame(move)
</script>
</body>
</html>