canvas绘制时钟

387 阅读1分钟

效果图如下(时钟为动态):

image.png

基本结构如下

    <style>
        #myCanvas{
            background-color: rgb(212, 201, 197);
        }
    </style>

    <body>
        <canvas id="myCanvas" width="200" height="200"></canvas>
    </body>

逻辑代码如下:

    <script>
        /** @type {HTMLCanvasElement} */
        let myCanvas = document.getElementById('myCanvas')
        let ms = myCanvas.getContext('2d')
        function clock(){
            ms.clearRect(0,0,200,200)
            ms.strokeStyle = 'black'
            ms.save();
            //绘制表盘
            ms.beginPath();
            ms.arc(100,100,99,0*Math.PI/6,12*Math.PI/6,true)
            ms.stroke();//绘制
            ms.closePath()
            ms.translate(100,100);
            ms.rotate(-2*Math.PI/4)
            ms.save()//保存旋转圆心
            
            //绘制刻度
            for(let i=1;i<13;i++){
                ms.rotate(Math.PI/6);
                ms.beginPath();
                ms.lineWidth=3
                ms.moveTo(80,0);
                ms.lineTo(100,0)
                ms.stroke();//绘制
                ms.closePath();//关闭路径
            }
            
            for(let j=1;j<61;j++){
                ms.rotate(Math.PI/30);
                if(j%5===0) continue
                ms.beginPath();
                ms.lineWidth=1
                ms.moveTo(90,0);
                ms.lineTo(99,0)
                ms.stroke();//绘制
                ms.closePath();//关闭路径
            }
            
            let time =new Date();
            let hour = time.getHours();
            let min = time.getMinutes();
            let sec = time.getSeconds();
            hour=hour>12?(hour-12):hour

            ms.save();
            //绘制秒针
            ms.beginPath();
            ms.strokeStyle = 'red'
            ms.rotate(2*Math.PI/60*sec);
            ms.moveTo(-15,0);
            ms.lineTo(74,0);
            ms.stroke();
            ms.closePath();
            ms.restore();
            
            ms.save();
            //绘制分针
            ms.beginPath();
            ms.strokeStyle = 'green'
            ms.lineWidth=2
            ms.rotate(2*Math.PI/60*min+2*Math.PI/3600*sec);
            ms.moveTo(-10,0);
            ms.lineTo(55,0);
            ms.stroke();
            ms.closePath();
            ms.restore();
            
            ms.save();
            //绘制时针
            ms.beginPath();
            ms.lineWidth=3
            ms.strokeStyle = 'blue'
            ms.rotate(2*Math.PI/12*hour+2*Math.PI/720*min);
            ms.moveTo(-5,0);
            ms.lineTo(30,0);
            ms.stroke();
            ms.closePath();
            ms.restore();
            
            //绘制中心原点
            ms.beginPath()
            ms.arc(0,0,5,0,2*Math.PI)
            ms.fillStyle = "red"
            ms.fill()
            ms.closePath()
            ms.restore();
            ms.restore();
        }
        setInterval(function(){
            clock()
        },1000)
    </script>