search
HomeWeb Front-endJS TutorialHow to use JS to realize the parabolic trajectory motion of a small ball

This article mainly introduces two methods of realizing the parabolic trajectory motion of a JS ball. It analyzes the relevant calculation and graphics drawing operation skills of javascript to realize the parabolic trajectory of a small ball in the form of examples. Friends in need can refer to the following

The examples in this article describe two methods of realizing the parabolic trajectory motion of the JS ball. Share it with everyone for your reference, the details are as follows:

The general idea of ​​​​implementing the parabolic trajectory motion of the ball in js:

1. Use the setInterval() method to perform interval Refresh, update the position of the ball to achieve dynamic effects
2. Draw the ball and the sports area. The sports area can be vertically centered through flex layout
3. Use the physical formulaS(y)=1/ 2*g*t*t, S(x)=V(x)t to calculate the path
is now determinedV(x)=4m/s, The refresh interval is set to 0.1s. Originally, the conversion between px and meters is different for different sizes. In this example, a 17-inch monitor is used, which is about 1px=0.4mm. However, the browser is too small, so it can only simulate a parabolic trajectory. In this example, the distance between px and meters is reduced to 100 times.

The first method: draw the ball through border-radius

Idea: use border-radius: 50% Draw the ball, set relative to the ball, calculate the current position of the ball each time, and assign it to top and left. When calculating the motion trajectory, the variable can be incremented to calculate the number of setInterval calls, each time is 0.1s, so that the total time can be calculated. The code is as follows:

<!DOCTYPE>
<html>
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title></title>
  <style type="text/css">
  /*给body进行flex布局,实现垂直居中*/
  body {
  min-height: 100vh;/*高度适应浏览器高度*/
  display: flex;
  justify-content: center;/*水平居中*/
  align-items: center;/*垂直居中*/
    font-size: 20px;
    font-weight: bold;
  }
  /*设置运动区域*/
  #bg {
    width: 600px;
    height: 600px;
    border: 2px solid #e0e0e0;
    border-radius: 4px;/*给p设置圆角*/
    padding: 20px;
  }
  /*生成小球,并定义初始位置*/
  #ball {
    border-radius: 50%;/*可把正方形变成圆形,50%即可*/
    background: #e0e0e0;
    width: 60px;
    height: 60px;
    position: relative;
    top: 30px;
    left: 30px;
  }
  button {
    width: 80px;
    height: 30px;
    border-radius: 4px;
    color: #fff;
    background: #AA7ECC;
    font-size: 20px;
    font-weight: bold;
    margin-left: 20px;
  }
  </style>
</head>
<body>
<p id="bg">
  此时水平速度为:4<button onclick="start()">演示</button>
  <p id="ball"></p>
</p>
<script type="text/javascript">
function start(){
  var x,y,k=1,t;
  //x是水平方向移动路径;y是垂直方向的;k记录次数,可与0.1相乘得时间;t记录setInterval的返回id,用于clearInterval
  t = setInterval(function(){
  x = 30+0.1*k*4*100;
    //S(x)=S(0)+t*V(x),100是自定义的米到px转换数
    y = 30+1/2*9.8*0.1*k*0.1*k*100;//S(y)=S(0)+1/2*g*t*t
  var j = document.getElementById("ball");
    //通过修改小球的top和left,修改小球的位置
    j.style.top = y;
    j.style.left = x;
  k++;//每次调用,k自增,简化计算
  if(x>480||y>480){
  clearInterval(t);//小球达到边界时,清除setInterval
  }
  },100);//每0.1s调用一次setInterval的function
}
</script>
</body>
</html>

Second type: canvas in h5 draws the ball and sports area

Idea: Use canvas to draw the ball, Since the ball cannot move through top and left, it needs to clear the canvas with clearRect every time it is called, and then draw the ball at the calculated position. The code is as follows:

<!DOCTYPE>
<html>
<head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title></title>
  <style type="text/css">
  body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  }
  #myCanvas {
  box-shadow: -2px -2px 2px #efefef,5px 5px 5px #b9b9b9;
  }
  </style>
</head>
<body>
<canvas id="myCanvas" width="600px" height="600px"></canvas>
<script type="text/javascript">
var x=50,y=50,k=1;
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
cxt.fillStyle="#e0e0e0";
cxt.beginPath();
cxt.arc(x,y,30,0,Math.PI*2,true);
cxt.closePath();
cxt.fill();
t=setInterval("parabola()",100);
function parabola(){
  cxt.clearRect(0,0,600,600);//清除原始图形
  cxt.beginPath();
  x=50+0.1*k*4*100;y=50+9.8*0.1*k*0.1*k*1/2*100;
  cxt.arc(x,y,30,0,Math.PI*2,true);
  cxt.closePath();
  cxt.fill();
  k++;
  if(x>520||y>520){
  clearInterval(t);
  }
}
</script>
</body>
</html>

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement a web version of the calculator in JS

How to remove the # sign in the url in Angular2 ( Detailed tutorial)

How to use the mobile component library in Vue.js (detailed tutorial)

The above is the detailed content of How to use JS to realize the parabolic trajectory motion of a small ball. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool