Canvas绘制时钟

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>qdabc.cn</title>
    <style>
        canvas{
            border: 1px solid #000;
        }
    </style>
</head>
<body>

        <canvas id="canvas" width="600" height="400"></canvas>

</body>
<script>

    var canvas=document.getElementById('canvas'),
    ctx=canvas.getContext('2d');

    

    function toDraw(){
        var x=200,
            y=200,
            r=150;

        /*每次调用都删除一下*/
            ctx.clearRect(0,0,ctx.width,ctx.height);

        /*获取时间*/
        var oDate=new Date(),
            oHours=oDate.getHours(),
            oMin=oDate.getMinutes(),
            oSen=oDate.getSeconds();

        var oHoursValue=(-90+oHours*30+oMin/2)*Math.PI/180;
        var oMinValue=(-90+oMin*6)*Math.PI/180;
        var oSenValue=(-90+oSen*6)*Math.PI/180;

        /*获取60个刻度*/
        ctx.beginPath();
        for(var i=0;i<60;i++){
            ctx.moveTo(x,y);
            ctx.arc(x,y,r,6*i*Math.PI/180,6*(i+1)*Math.PI/180,false)
        }
        ctx.closePath();
        ctx.stroke();

        /*白色遮罩层*/
        ctx.fillStyle='white';
        ctx.beginPath();
         ctx.moveTo(x,y);
        ctx.arc(x,y,r*19/20,0,360*(i+1)*Math.PI/180,false)
        ctx.closePath();
        ctx.fill();

        /*,每5分钟的刻度会粗一丢*/
        ctx.lineWidth=3;
        ctx.beginPath();
        for(var i=0;i<12;i++){
            ctx.moveTo(x,y);
            ctx.arc(x,y,r,30*i*Math.PI/180,30*(i+1)*Math.PI/180,false)
        }
        ctx.closePath();
        ctx.stroke();

        /*再盖一个白色圆盘*/
        ctx.fillStyle='white';
        ctx.beginPath();
        ctx.moveTo(x,y);
        ctx.arc(x,y,r*18/20,0,360*(i+1)*Math.PI/180,false)
        ctx.closePath();
        ctx.fill();

        /*时针*/
        ctx.lineWidth=5;
        ctx.beginPath();
        ctx.moveTo(x,y);
        ctx.arc(x,y,r*10/20,oHoursValue,oHoursValue,false)
        ctx.closePath();
        ctx.stroke();

        /*分针*/
        ctx.lineWidth=3;
        ctx.beginPath();
        ctx.moveTo(x,y);
        ctx.arc(x,y,r*14/20,oMinValue,oMinValue,false)
        ctx.closePath();
        ctx.stroke();

        /*秒针*/
        ctx.lineWidth=1;
        ctx.beginPath();
        ctx.moveTo(x,y);
        ctx.arc(x,y,r*19/20,oSenValue,oSenValue,false)
        ctx.closePath();
        ctx.stroke();
    }
    /*每一秒执行一次*/

    setInterval(toDraw,1);

    toDraw();


</script>
</html>

欢迎分享本文,转载请保留出处:前端ABC » Canvas绘制时钟

分享到:更多 ()

发表评论 0