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!

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

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.

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

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.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
