时钟demo

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title></title>
<!--<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>-->
<style type="text/css">
* {
padding: 0;
margin: 0;
}

.box {
background: blue;
width: 100px;
height: 100px;
}
</style>

</head>

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

<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var hours, minutes, seconds;
ctx.translate(250, 250);

function drawTime() {
ctx.clearRect(-250, -250, 1000, 1000);
var now = new Date();
hours = now.getHours();
minutes = now.getMinutes();
seconds = now.getSeconds();
hours = hours > 12 ? hours - 12 : hours;
hours += minutes / 60;
minutes += seconds / 60;
ctx.strokeStyle = "#0000FF"
ctx.lineWidth = 10;
ctx.beginPath();
ctx.arc(0, 0, 200, 0, 360, false);
ctx.closePath();
ctx.stroke();
for (var i = 0; i < 12; i++) {
ctx.save();
ctx.beginPath();
ctx.rotate(i * 30 * Math.PI / 180);
ctx.lineWidth = 5;
ctx.strokeStyle = "black";
ctx.moveTo(0, -170);
ctx.lineTo(0, -190);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
for (var i = 0; i < 60; i++) {
ctx.save();
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.rotate(i * 6 * Math.PI / 180);
ctx.moveTo(0, -180);
ctx.lineTo(0, -190);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
//时针
ctx.save();
ctx.strokeStyle = "black";
ctx.lineWidth = 5;
ctx.beginPath();
ctx.rotate(hours * 30 * Math.PI / 180);
ctx.moveTo(0, 10);
ctx.lineTo(0, -100);
ctx.stroke();
ctx.closePath();
ctx.restore();
//分针
ctx.save();
ctx.strokeStyle = "black";
ctx.lineWidth = 4;
ctx.beginPath();
ctx.rotate(minutes * 6 * Math.PI / 180);
ctx.moveTo(0, 10);
ctx.lineTo(0, -170);
ctx.stroke();
ctx.closePath();
ctx.restore();
//秒针
ctx.save();
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.rotate(seconds * 6 * Math.PI / 180);
ctx.moveTo(0, 10);
ctx.lineTo(0, -170);
ctx.closePath();
ctx.stroke();
//秒针前端小圆圈
ctx.beginPath();
ctx.arc(0, -150, 5, 0, 360, false);
ctx.closePath();
ctx.fillStyle = "white";
ctx.fill();
ctx.stroke();
ctx.restore();
//3针交叉点
ctx.beginPath();
ctx.arc(0, 0, 5, 0, 360, false);
ctx.closePath();
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.fillStyle = "gray";
ctx.fill();
ctx.stroke();
}
drawTime();
setInterval(drawTime, 1000);
</script>
</body>

</html>

posted @ 2016-02-01 17:06  cj伤风  阅读(180)  评论(0编辑  收藏  举报