在JavaScript中实现小球的运动,通常涉及到HTML5的Canvas绘图技术和JavaScript的动画循环。下面是一个简单的示例,展示了如何实现一个小球在Canvas上移动的效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>小球运动示例</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script src="script.js"></script>
</body>
</html>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let x = canvas.width / 2;
let y = canvas.height - 30;
let dx = 2;
let dy = -2;
const ballRadius = 10;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
x += dx;
y += dy;
}
setInterval(draw, 10);
canvas
元素,用于绘制小球。canvas
元素和绘图上下文。(x, y)
,移动速度(dx, dy)
,以及半径ballRadius
。drawBall
函数用于绘制小球。draw
函数用于清除画布、绘制小球,并更新小球的位置。如果小球碰到画布的边界,则反转其移动方向。setInterval
函数每10毫秒调用一次draw
函数,实现动画效果。通过这种方式,你可以实现一个基本的小球运动动画,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云