<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CANVAS 时钟</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
canvas {
box-shadow: 0 0 10px 10px #CCCCCC;
display: block;
margin: 50px auto 0;
}
</style>
<script type="text/javascript">
window.onload = function() {
new canvasClock({
canvas: document.getElementById("canvas"),
r: 100,
h: [0, -30],
m: [0, -60],
s: [0, -90]
})
};
function canvasClock(opts) {
var self = this;
self.r = opts.r;
self.h = opts.h;
self.m = opts.m;
self.s = opts.s;
self.PI = Math.PI;
self.canvas = opts.canvas;
self.context = self.canvas.getContext("2d");
//创建12格子
window.setInterval(function() {
self.canvas.width = 0; self.canvas.height = 0; self.canvas.width = 400; self.canvas.height = 400;
self.timeSplit();
self.createTime("m");
self.createTime("h");
self.createTime("s")
},
1000)
};
canvasClock.prototype = {
timeSplit:function()
{
var self=this;
self.context.translate(self.r * 2, self.r * 2);
self.context.strokeStyle = "black";
for(var i=0;i<12;i++){
self.context.rotate(30*Math.PI/180);
self.context.moveTo(0,-90);
self.context.lineTo(0,-70);
self.context.fillText(i+1,-3,-60);
}
self.context.stroke();
},
createTime: function(str) {
var self = this;
var context = self.context;
context.lineWidth = 8;
context.beginPath();
context.arc(0, 0, self.r, 0, 2 * self.PI, true);
context.strokeStyle = "red";
context.stroke();
context.closePath();
context.strokeStyle = "green";
var s = (new Date()).getSeconds();
var m = (new Date()).getMinutes();
var h = (new Date()).getHours();
if (str == "s") {
var t = s * 6;
var x = self.s[0];
var y = self.s[1]
} else if (str == "m") {
var t = (m + s / 60) * 6;
var x = self.m[0];
var y = self.m[1]
} else {
var t = (h + m / 60) * 30;
var x = self.h[0];
var y = self.h[1]
}
context.lineWidth = 6;
context.lineCap = "round";
context.rotate(t * self.PI / 180);
context.beginPath();
context.moveTo(0, 0);
context.lineTo(x, y);
context.stroke();
context.closePath()
}
}
</script>
</head>
<body>
<canvas width="400" height="400" id="canvas"></canvas>
</body>
</html>
说明:第一:rotate 旋转角度会叠加。 第二个注意点是:它是以中心点为旋转中心的(画板左上角)。要用context.translate 来定位新的坐标才行。否则会出现中心点(你以为的中心点,比如圆心)移动的情况。