用Canvas创造一个太阳系

1,179 阅读2分钟

canvas绘制动画效果如图:


二话不说上代码,慰劳

<!DOCTYPE HTML>
<html>
<body>

<canvas id="sun" width="300" height="300" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">
    var sun = new Image();
    var moon = new Image();
    var earth = new Image();
    function init(){
        sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
        moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
        earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
        window.requestAnimationFrame(draw);
    }

    function draw() {
        var ctx = document.getElementById('sun').getContext('2d');

        ctx.globalCompositeOperation = 'destination-over';   //在源图像上方显示目标图像。
        ctx.clearRect(0,0,300,300); // clear canvas

        ctx.save();
        ctx.translate(150,150);
        ctx.save();

        // Earth
        var time = new Date();
        //根据时间旋转地球,旋转圆心为新的原点(150,150)       
        ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );   
        ctx.translate(105,0);        //105为地球轨道半径,此处也为当前原点
        ctx.fillStyle = 'rgba(0,0,0,0.4)';    //地球背光面阴影颜色
        ctx.fillRect(0,-12,15,24);      // Shadow表示地球相对太阳的背光面矩形区域  fillRect(x,y,width,height);
        ctx.drawImage(earth,-12,-12);   //drawImage(img,x,y);x,y表示图像的左上角对应放置位置,12为地球图片的半径

        // Moon
        ctx.beginPath();
        ctx.strokeStyle = 'grey';    //月球轨道线条颜色
        ctx.arc(0,0,28.5,0,Math.PI*2,false); // Moon轨道(此处圆心为(0,0),但是此处的原点早已移动到)
        ctx.stroke(); 
        ctx.save();
        //当前旋转原点为地球中心,(150,150)+(105,0)        
        ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );  
        ctx.translate(0,28.5);     //画点位置移动,28.5为月球围绕地球的轨道半径
        ctx.drawImage(moon,-3.5,-3.5);    //3.5为月球半径大小
        ctx.restore();

        ctx.restore();   //此处restore还原的是第28行的save状态
        ctx.beginPath();
        ctx.strokeStyle = 'rgba(0,153,255,0.4)';    //地球轨道线条颜色
        ctx.arc(0,0,105,0,Math.PI*2,false); // Earth orbit轨道
        ctx.stroke();
        
        ctx.restore();    //此处restore还原的是第26行的save状态
        
        /*Sun(若看不清画布情况就注销该句则可观察到)*/
        ctx.drawImage(sun,0,0,300,300);

        window.requestAnimationFrame(draw);
    }

    init();

    /*rotate旋转的圆心要注意,且当一开始思路不清晰的时候,就把该句注销,好观察画布*/
</script>

</body>
</html>