当前位置: 代码迷 >> HTML/CSS >> HTML5 Canvas画钟表
  详细解决方案

HTML5 Canvas画钟表

热度:462   发布时间:2012-11-26 11:48:49.0
HTML5 Canvas画时钟



?<!DOCTYPE html>

<html>
<head>
    <title></title>
    <script type="text/javascript">
        function draw() {
            var canvas = document.getElementById("clockCanvas");
            var ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, 200, 200);
            ctx.save();
            ctx.translate(100, 100);
            ctx.font = "Bold 14px Arial";
            
            for (var i = 1; i <=60; i++) {
                var angle = Math.PI / 30 * i;
                var sin = Math.sin(angle);
                var cos = Math.cos(angle);
                if (i % 5 == 0) {
                    ctx.lineWidth = 4;
                    var sx = sin * 80;
                    var sy = cos * -80;
                    ctx.fillText(i/5, sin * 70-8, cos * -72+5);
                } else {
                    ctx.lineWidth = 2;
                    var sx = sin * 90;
                    var sy = cos * -90;
                }

                var ex = sin * 100;
                var ey = cos * -100;
                ctx.beginPath();
                ctx.moveTo(sx, sy);
                ctx.lineTo(ex, ey);
                ctx.stroke();
            }
            var currentDate = new Date();
            var second = currentDate.getSeconds();
            var hour = currentDate.getHours();
            var minute = currentDate.getMinutes();

            ctx.save();
            ctx.rotate(Math.PI / 6 * (hour+minute/60+second/3600));
            ctx.beginPath();
            ctx.moveTo(0, 20);
            ctx.lineTo(0, -55);
            ctx.stroke();


            ctx.restore();
            ctx.save();

            ctx.rotate(Math.PI / 30 * (minute + second / 60));
            ctx.beginPath();
            ctx.moveTo(0, 20);
            ctx.lineTo(0, -75);
            ctx.stroke();


            ctx.restore();
            ctx.rotate(Math.PI / 30 * second);
            ctx.strokeStyle = "#FF0000";
            ctx.beginPath();
            ctx.moveTo(0, 20);
            ctx.lineTo(0, -90);
            ctx.stroke();

            ctx.restore();
            setTimeout(draw, 1000)
        }
    </script>
</head>
<body onload="draw()">
<canvas id="clockCanvas" width="200" height="200" style="border:1px solid red"></canvas>
</body>
</html>
?