html5 canvas绘制钟表
终于没有兼容bug了 。。。
[html]
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></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");
window.setInterval(function() {
self.canvas.width = 0;
self.canvas.height = 0;
self.canvas.width = 400;
self.canvas.height = 400;
self.context.strokeStyle = "rgba(255,0,0,0.1)";
self.context.translate(self.r * 2, self.r * 2);
self.createTime("m");
self.createTime("h");
self.createTime("s")
},
1000)
};
canvasClock.prototype = {
createTime: function(str) {
var self = this;
var context = self.context;
context.lineWidth = 1;
context.beginPath();
context.arc(0, 0, self.r, 0, 2 * self.PI, true);
context.stroke();
context.closePath();
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 = 10;
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>
摘自 事与愿违
补充:web前端 , HTML 5 ,