canvas实现动态时钟

2023-11-20T09:25:26.png

    <canvas id="can" width="500" height="500" style="background-color: pink;">

    </canvas>
   
</body>
<script>
    function showTime(){
        var now = new Date();
    var hours = now.getHours();
    var mins = now.getMinutes();
    var secs = now.getSeconds();
    hours = hours + mins/60;
    // 获取画布
    var canvas = document.getElementById("can")
    // 获取画笔
    var g = can.getContext("2d");
    //清理画布
    g.clearRect(0, 0, canvas.width, canvas.height);
    // 开启路径
    g.beginPath();
    g.strokeStyle = "white";
    g.lineWidth =2;
    g.arc(250, 250, 250, 0, Math.PI * 2, true)
    g.stroke();
    g.closePath();
    //表盘
    for(var i=0; i<12;i++){ 
    g.save();
    g.translate(250,250);
    g.beginPath();
    g.rotate(i*30*Math.PI/180)

    g.strokeStyle="red";
    g.lineWidth=5;
    g.moveTo(0,-225);
    g.lineTo(0,-205);
    g.stroke();
    g.closePath();
    g.restore();
}
    //时针
    g.save();
    g.translate(250,250);
    g.beginPath();
    g.rotate(hours*30*Math.PI/180);
    g.strokeStyle="red";
    g.lineWidth=7;
    g.moveTo(0,-50);
    g.lineTo(0,-0);
    g.stroke();
    g.closePath();
    g.restore();
     //分针
    g.save();
    g.translate(250,250);
    g.beginPath();
    g.rotate(mins*6*Math.PI/180);
    g.strokeStyle="red";
    g.lineWidth=5;
    g.moveTo(0,-100);
    g.lineTo(0,0);
    g.stroke();
    g.closePath();
    g.restore();
    //秒针
    g.save();
    g.translate(250,250);
    g.beginPath();
    g.rotate(secs*6*Math.PI/180);
    g.strokeStyle="red";
    g.lineWidth=3;
    g.moveTo(0,-160);
    g.lineTo(0,10);
    g.stroke();
    g.closePath();
    g.restore();
    }
    //每秒执行一次
    setInterval(showTime,1000);
    //先执行一次,消除延迟
    showTime();
</script>

微信公众号:梦溪博客
最后修改:2023 年 11 月 20 日
如果觉得我的文章对你有用,请随意赞赏