日期:2014-05-17  浏览次数:20558 次

HTML5 Canvas做的时钟

?

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>HTML5 demo</title> 
    <style>
        .clock {
            width: 600px;
            height: 600px;
            border: 2px dotted red;
            border-radius: 20px;
            background: url('clockface.jpg') no-repeat;
        }
    </style>
</head>
<body>    
    <div class="clock">
        <canvas id="canvas" width="600" height="600">Not supported</canvas>
    </div>
</body>
<script type="text/javascript">
    startClock();
      
    function $(id) {
        return document.getElementById(id);
    }
     
    function startClock() {
        setInterval("drawClock()", 1000);
    }
    
    function computePostions() {
        var time = new Date();
        var ss = time.getSeconds() / 60;
        var mm = (time.getMinutes() + ss) / 60;
        var hh = (time.getHours() + mm) / 12;
        return {
            'h': (hh * 2 + 1) * Math.PI,
            'm': (mm * 2 + 1) * Math.PI,
            's': (ss * 2 + 1) * Math.PI
        };
    }
    
    function drawClock() {
        var pos = computePostions();
        
        var ctx = $('canvas').getContext('2d');
        ctx.clearRect(0, 0, 600, 600);

        // hour
        ctx.save();
        ctx.beginPath();
        ctx.translate(300, 300);
        ctx.rotate(pos.h);
        ctx.strokeStyle = "#FBD10B";
        ctx.fillStyle = "#FBD10B";
        ctx.lineWidth = "3";
        ctx.moveTo(-4, 0);
        ctx.lineTo(0, 80);
        ctx.lineTo(4, 0);
        ctx.lineTo(-4, 0);
        ctx.fill();
        ctx.stroke();        
        ctx.closePath();
        ctx.restore();
              
        // minute
        ctx.save();
        ctx.beginPath();
        ctx.translate(300, 300);
        ctx.rotate(pos.m);
        ctx.strokeStyle = "#4CB549";
        ctx.fillStyle = "#4CB549";
        ctx.lineWidth = "2";
        ctx.moveTo(-3, 0);
        ctx.lineTo(0, 120);
        ctx.lineTo(3, 0);
        ctx.lineTo(-3, 0);
        ctx.fill();
        ctx.stroke();        
        ctx.closePath();
        ctx.restore();

        // second
        ctx.save();
        ctx.beginPath();
        ctx.translate(300, 300);
        ctx.rotate(pos.s);
        ctx.strokeStyle = "#CB0909";
        ctx.fillStyle = "#CB0909";
        ctx.lineWidth = "1";
        ctx.moveTo(0, 0);
        ctx.lineTo(0, 180);
        ctx.lineTo(0, 0);
        ctx.arc(0, 0, 10, 0, Math.PI * 2, true);
        ctx.fill();
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
    }
</script>
</html>