美文网首页
canvas 日月地转动

canvas 日月地转动

作者: huanghaodong | 来源:发表于2020-03-19 15:24 被阅读0次
image.png
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
canvas {
    border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="tutorial" width="500" height="500"></canvas>
<script type="text/javascript">
    var canvas = document.getElementById('tutorial');
    var ctx = canvas.getContext("2d");
    function draw(){
        ctx.clearRect(0, 0, 300, 300); //清空所有的内容
        ctx.save();
        /*背景*/
        ctx.beginPath();
        ctx.fillStyle = 'black'
        ctx.fillRect(0, 0, 300, 300)
        /*绘制 太阳*/
        let time = new Date();
        ctx.translate(150, 150);
        ctx.rotate(2 * Math.PI / 600 * time.getSeconds() + 2 * Math.PI / 600000 * time.getMilliseconds())
        ctx.beginPath();
        ctx.fillStyle = 'red'
        ctx.arc(0, 0, 50, 0, 2*Math.PI)
        ctx.fill()
        ctx.beginPath();
        ctx.fillStyle = 'black'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText('日', 0, 0)
        //绘制earth轨道
        ctx.beginPath();
        ctx.strokeStyle = "rgba(255,255,0,0.5)";
        ctx.arc(0, 0, 100, 0, 2 * Math.PI)
        ctx.stroke()
        //绘制地球
        ctx.rotate(2 * Math.PI / 60 * time.getSeconds() + 2 * Math.PI / 60000 * time.getMilliseconds())
        ctx.beginPath();
        ctx.fillStyle='blue'
        ctx.translate(100, 0)
        ctx.arc(0, 0, 20, 0, 2 * Math.PI)
        ctx.fill()
        ctx.beginPath();
        ctx.fillStyle = 'black'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText('地', 0, 0)
        //绘制月球轨道
        ctx.beginPath();
        ctx.strokeStyle = "rgba(255,255,255,.3)";
        ctx.arc(0, 0, 40, 0, 2 * Math.PI);
        ctx.stroke();
     
        //绘制月球
        ctx.rotate(2 * Math.PI / 6 * time.getSeconds() + 2 * Math.PI / 6000 * time.getMilliseconds());
        ctx.beginPath();
        ctx.fillStyle='yellow'
        ctx.arc(40, 0, 10, 0, 2 * Math.PI)
        ctx.fill()
        ctx.beginPath();
        ctx.fillStyle = 'black'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText('月', 40, 0)
        ctx.restore();
        requestAnimationFrame(draw);
    }
    draw()
</script>
</body>
</html>

相关文章

网友评论

      本文标题:canvas 日月地转动

      本文链接:https://www.haomeiwen.com/subject/fcdlyhtx.html