环绕动画-月亮绕地球,地球绕太阳

最终实现效果:

 代码实现如下:

<!DOCTYPE html>
<html  lang="en">
    <head>   
        <style>
            canvas {
                background-color: #545252;
                display:block;
                margin:0 auto;
            }
        </style>
    </head>
    <body>
        <script>
            const canvas = document.createElement("canvas")
            canvas.width = 800;
            canvas.height = 800; document.body.append(canvas)
            const context = canvas.getContext("2d");

            // 地球旋转的角度
            let earthAngle = 0;
            // 月亮旋转角度
            let moonAngle = 0;

            function loop() {
                context.save()

                context.clearRect(0, 0, canvas.width, canvas.height);

                // 太阳
                context.beginPath();
                context.arc(400,400,100,0,2*Math.PI);
                context.fillStyle ="#e3fa14"
                context.shadowColor = "#e3fa14"
                context.shadowBlur = 10;
                context.fill();
                context.closePath();

                // 地球
                context.beginPath();
                // 原点移动到正中心
                context.translate(400,400)
                // 画笔旋转一个角度
                // context.rotate(0 * Math.PI / 180)
                context.rotate((earthAngle+=0.3)*Math.PI/180)
                // 为了月亮动画,将原点移动到与地球中心一致位置
                context.translate(200,0)
                context.arc(0, 0, 20, 0, 2 * Math.PI);
                context.fillStyle="blue";
                context.shadowColor="blue";
                context.fill()
                context.closePath();

                // 月亮
                context.beginPath();
                context.fillStyle="#fff"
                context.rotate((moonAngle++) * Math.PI / 180)
                context.arc(40,0,6,0,2*Math.PI);
                context.fill();
                context.closePath();

                context.restore()
                requestAnimationFrame(loop)
            }
            requestAnimationFrame(loop)
        </script>
    </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值