微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html5 canvas 画时钟

<!DOCTYPE HTML>
<html>
<body>

<canvas id="myCanvas" width="400" height="400" style="border:1px solid"></canvas>

<script type="text/javascript">
    // get the canvas
    var myCanvas = document.getElementById("myCanvas");
    var ctx = myCanvas.getContext("2d");

    function showClock(){
        ctx.save();
        ctx.save();
        ctx.save();
        ctx.save();
        ctx.save();
        ctx.save();
        ctx.save();
        ctx.clearRect(0,400,400);

        // create the clock border
        ctx.restore();
        ctx.beginPath();
        ctx.strokeStyle="pink";
        ctx.linewidth=10;
        ctx.arc(200,200,150,Math.PI*2,true);
        ctx.stroke();


        // create the hour icon
        ctx.restore();
        ctx.linewidth=8;
        ctx.strokeStyle="blue";
        ctx.translate(200,200);
        for(var i=0;i<12;i++){
          ctx.beginPath();      
          ctx.moveto(135,0);
          ctx.lineto(150,0);
          ctx.rotate(Math.PI/6);
          ctx.stroke();
        }

        // create the minute icon
        ctx.restore();
        ctx.linewidth=4;
        ctx.strokeStyle="blue";
        ctx.translate(200,200);
        for(var i=0;i<60;i++){
          ctx.beginPath();      
          ctx.moveto(145,0);
          ctx.rotate(Math.PI/30);
          ctx.stroke();
        }

        var date = new Date();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        hour = hour>=12?hour-12:hour;
        
        // create the hour hand
        ctx.restore();
        ctx.linewidth = 14;
        ctx.strokeStyle="pink";
        ctx.translate(200,200);
        ctx.rotate(hour*(Math.PI/6) + (Math.PI/360)*minute + (Math.PI/21600)*second-Math.PI/2);
        ctx.beginPath();      
        ctx.moveto(-20,0);
        ctx.lineto(90,0);     
        ctx.stroke();
       

        // create the minute hand
        ctx.restore();
        ctx.linewidth = 10;
        ctx.strokeStyle="pink";
        ctx.translate(200,200);
        ctx.rotate((Math.PI/30)*minute + (Math.PI/1800)*second-Math.PI/2);
        ctx.beginPath();      
        ctx.moveto(-30,0);
        ctx.lineto(125,0);     
        ctx.stroke();

        // create the second hand
        ctx.restore();
        ctx.linewidth = 4;
        ctx.strokeStyle="pink";
        ctx.translate(200,200);
        ctx.rotate( (Math.PI/30)*second-Math.PI/2);
        ctx.beginPath();      
        ctx.moveto(-35,0);
        ctx.lineto(135,0);     
        ctx.stroke();

        ctx.restore();
        setTimeout(showClock,1000);
    }

showClock();
</script>
</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。