手记

用HTML5的canvas画会转动的时钟

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>时钟</title>
</head>

<body>
    <canvas id="canvas" height="600" width="600" >您的浏览器不支持canvas标签</canvas>
 <script type="text/javascript">

        var canvas = document.getElementById("canvas");
        var cxt = canvas.getContext("2d");
    //转动
    function moveTo(){
        cxt.clearRect(0,0,600,600);
        var date = new Date();
        var hour = date.getHours();
        var mins = date.getMinutes();
        var sec = date.getSeconds();            

    //时刻
    for(var i=0;i<12;i++){
        cxt.save();
        cxt.lineWidth=2;
        cxt.translate(300,300);
        cxt.rotate(i*30*Math.PI/180);
        cxt.beginPath();
        cxt.moveTo(0,-170);
        cxt.lineTo(0,-190);
        cxt.closePath();
        cxt.stroke();
        cxt.restore();
    }       

    //分刻
    for(var i=0;i<60;i++){
        cxt.save();
        cxt.lineWidth=1;
        cxt.translate(300,300);
        cxt.rotate(i*6*Math.PI/180);
        cxt.beginPath();
        cxt.moveTo(0,-180);
        cxt.lineTo(0,-190);
        cxt.closePath();
        cxt.stroke();
        cxt.restore();
    }
    //表盘
        cxt.beginPath();
        cxt.lineWidth=5;
        cxt.arc(300,300,200,0,360,false);
        cxt.stroke();
        cxt.closePath();

    //时针
        cxt.beginPath();
        cxt.save();
        cxt.lineWidth=3;
        cxt.translate(300,300);
        cxt.rotate(hour*6*Math.PI/180);
        cxt.moveTo(0,-100);
        cxt.lineTo(0,10);
        cxt.stroke();
        cxt.closePath();
        cxt.restore();  
    //分针
        cxt.beginPath();
        cxt.save();
        cxt.lineWidth=2;
        cxt.translate(300,300);
        cxt.rotate(mins*6*Math.PI/180);
        cxt.moveTo(0,-150);
        cxt.lineTo(0,15);
        cxt.stroke();
        cxt.closePath();
        cxt.restore();          
    //秒针
        cxt.beginPath();
        cxt.save();
        cxt.lineWidth=1;
        cxt.translate(300,300);
        cxt.rotate(sec*Math.PI/30);
        cxt.moveTo(0,-165);
        cxt.lineTo(0,20);   
        cxt.stroke();
        cxt.closePath();
        cxt.restore();  

    //中间点
        cxt.save();
        cxt.translate(300,300);
        cxt.beginPath();
        cxt.arc(0,0,3,0,360,false);
        cxt.fill();
        cxt.closePath();
        cxt.stroke();
        cxt.restore();          
    }
    setInterval("moveTo()",1000);

</script>
</body>
</html>
4人推荐
随时随地看视频
慕课网APP

热门评论

怎么弄成时间与系统同步呢?

查看全部评论