如何使用HTML和JavaScript构建一个弹跳球
使用HTML、CSS和JavaScript可以创建一个弹跳球,并对该球执行一些弹跳操作。您可以阅读相关文章了解 如何使用CSS实现平滑弹跳动画。
本文将分为两部分,第一部分将决定弹跳球将执行弹跳的区域,基本上我们将创建一个画布,在该画布上进行弹跳。第二部分将设计弹跳球并为其添加一些弹跳功能。
HTML & CSS: HTML和CSS代码用于创建一个可以让球反弹的画布区域。我们将使用一个canvas标签,在JavaScript中使用圆形struct创建该画布中的球。画布区域和画布区域的背景颜色由CSS定义。
JavaScript: 这是本文的核心部分,我们将struct球并执行反弹任务。我们将分配4个变量,2个用于创建的圆形(球)坐标,另外两个用于弹跳球的各自速度。半径变量用于球的半径。我们还需要清除画布区域,为此我们将使用clearReact()函数。反弹和协调都将由math.random()函数决定。
示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
Bouncing Ball!!
</title>
<style>
h1 {
color: green;
}
canvas {
background-color: #F08080;
width: 600px;
height: 400px;
position: absolute;
top: 20%;
left: 20%;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Bouncing ball using JavaScript</h3>
<canvas>
</canvas>
</center>
</body>
</html>
Javascript代码
<script>
var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var l = canvas.getContext('2d');
// x and y are the coordinates of the circle
// vx and vy are the respective speeds
var x = Math.floor(Math.random() * innerWidth);
var y = Math.floor(Math.random() * innerHeight);
var vx = Math.floor(Math.random() * 2);
var vy = Math.floor(Math.random() * 4);
var radius = 20;
move();
// This function will do the animation
function move() {
requestAnimationFrame(move);
// It clears the specified pixels within
// the given rectangle
l.clearRect(0, 0, innerWidth, innerHeight);
// Creating a circle
l.beginPath();
l.strokeStyle = "black";
l.arc(x, y, radius, 0, Math.PI * 2, false);
l.stroke();
// Conditions so that the ball bounces
// from the edges
if (radius + x > innerWidth)
vx = 0 - vx;
if (x - radius < 0)
vx = 0 - vx;
if (y + radius > innerHeight)
vy = 0 - vy;
if (y - radius < 0)
vy = 0 - vy;
x = x + vx;
y = y + vy;
}
</script>
输出: