Two JS methods to realize parabolic trajectory movement of small balls
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 who need it can refer to it. I hope it can help. Everyone.
js The general idea of implementing the ball's parabolic trajectory motion:
1. Use the setInterval()
method to perform interval refresh and update the ball position to achieve dynamic Effect
2. Draw the ball and the sports area. The sports area can be vertically centered through flex layout
3. Use the physical formula S(y)=1/2*g*t*t , S(x)=V(x)t to calculate the path
Now it is determined thatV(x)=4m/s, and the refresh time 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 with 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>
Both methods can be implemented. The calculation methods are the same, but the methods are different. The first one is partial to CSS, using border-radius and dynamically modifying the DOM. The second one uses canvas to draw graphics. The drawing process should be carefully studied.
Related recommendations:
Code case for parabolic motion of elastic potential energy animation in JavaScript
js implements special effects of product parabola added to shopping cart javascriptTips_
Add to shopping cart parabolic animation effect based on jquery fly plug-in_jquery
The above is the detailed content of Two JS methods to realize parabolic trajectory movement of small balls. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment