DEV Community

CHENG QIAN
CHENG QIAN

Posted on

计算机模拟地月系统

B站视频讲解

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>月亮和地球</title>
</head>
<style>
#earth{width:0px;height:0px;border:24px solid orange;position:relative;top:325px; left:50%;margin-top:-12px;margin-left:-12px; border-radius:50%;}
#moon{width:14px; height:14px; border-radius:50%; background:red;  margin-left:-7px;margin-top:-7px; position:absolute;}
</style>
<body>
    <div id='earth'>
        <div style='width:600px;height:1px; background:red; position:absolute;'></div>
        <div style='width:1px;height:400px; background:black; position:absolute;left:400px;top:-200px'></div>
        <div id='moon'></div>
        <div id='gj'></div>
    </div>
    <script>
        var earth=document.getElementById('earth');
        var moon=document.getElementById('moon');
        var gj=document.getElementById('gj');
        var count=0;     //计步器,用于计算走几个dt画一次轨迹点
        var G=100000;  //万有引力常数
        var m1=100;//地球的质量
        var m2=1;//月亮的质量
        var x=400;   //月亮的x轴坐标
        var y=0;     //月亮的y轴坐标
        var r=Math.sqrt(x*x+y*y); //月亮到月亮的初始距离
        var ax=(-x*m1/(r*r*r))*G;   //月亮在x轴方向的初始加速度
        var ay=(-y*m1/(r*r*r))*G;  //月亮在y轴方向的初始加速度
        var vx=0;         //月亮在x轴方向的初始速度分量
        var vy=60;       //月亮在y轴方向的初始速度分量
        var dt=10;        //取的微分的间隔时间,在此期间把万有引力看作近似不变,以得到近似轨迹;单位是毫秒
        var split=100;   //把dt再平均分多少份,以用更短的时间求更精确的值
        moon.style.left=x+'px';  //给月亮的x坐标赋值,浏览器显示用
        moon.style.bottom=y+'px';   //给月亮的y坐标赋值,浏览器显示用
        setInterval(move,dt);

        function move(){
            var st=dt/(split*1000);//毫秒换算成秒的单位

            for(i=0;i<split;i++){
                x=x+vx*st;
                y=y+vy*st;
                r=Math.sqrt(x*x+y*y);
                ax=(-x*m1/(r*r*r))*G;
                ay=(-y*m1/(r*r*r))*G;
                vx=vx+ax*st;
                vy=vy+ay*st;
            }

            moon.style.left=x+'px';
            moon.style.bottom=y+'px';

            //添加轨迹元素
            var numgj=gj.getElementsByTagName('div');

            count++;
            var obj='<div style="width:4px;z-index:-1; height:4px;position:absolute;background:orange;left:'+x+'px;bottom:'+y+'px;"></div>';
            if(count%10==0){
                gj.innerHTML+=obj;
            }


        }



    </script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

Top comments (0)