使用canvas绘制一个显示实时时间的时钟
<div>
<canvas height="400" width="500" style="border: 1px solid red; background: whitesmoke;"></canvas>
</div>
<script type="text/javascript">
//绘制表盘
function setDial(obj, x, y, r, w) {
x = x ? x : 0;
y = y ? y : 0;
r = r ? r : 0;
if (w == 1)
obj.strokeStyle = "brown";
else
obj.strokeStyle = "black";
obj.rotate(r * Math.PI / 180);
obj.beginPath();
obj.lineWidth = w;
obj.moveTo(x, y);
obj.lineTo(x, y + 10);
obj.stroke();
}
//绘制时分秒
function setTimeHand(obj) {
//时
obj.restore();
obj.save();
obj.strokeStyle = "black";
obj.beginPath();
obj.lineWidth = 6;
let h = 0.5 * ((new Date).getHours() * 60 + (new Date).getMinutes() + 360) * Math.PI / 180;
obj.rotate(h);
obj.moveTo(0, 0);
obj.lineTo(0, 75);
obj.stroke();
//分
obj.restore();
obj.save();
obj.strokeStyle = "green";
obj.beginPath();
obj.lineWidth = 4;
let m = 0.1 * ((new Date).getMinutes() * 60 + (new Date).getSeconds() + 1800) * Math.PI / 180;
obj.rotate(m);
obj.moveTo(0, 0);
obj.lineTo(0, 85);
obj.stroke();
//秒
obj.restore();
obj.save();
obj.strokeStyle = "red";
obj.beginPath();
obj.lineWidth = 2;
let s = 0.006 * ((new Date).getSeconds() * 1000 + (new Date).getMilliseconds() + 30000) * Math.PI / 180;
obj.rotate(s);
obj.moveTo(0, 0);
obj.lineTo(0, 95);
obj.stroke();
obj.restore();
obj.save();
//毫秒
obj.restore();
obj.save();
obj.strokeStyle = "red";
obj.beginPath();
obj.lineWidth = 15;
let ms = 0.36 * ((new Date).getMilliseconds() + 500) * Math.PI / 180;
obj.rotate(ms);
obj.moveTo(0, 111);
obj.lineTo(0, 113);
obj.stroke();
obj.restore();
obj.save();
}
var con = $('canvas')[0].getContext('2d');
con.translate(245, 195);
con.save();
var timmer_1 = setInterval(function () {
con.translate(-245, -195);
con.clearRect(0, 0, 500, 400);
con.restore();
con.save();
//小刻度
setDial(con, 0, 100, 0, 3);
for (var i = 1; i < 60; i++)
setDial(con, 0, 100, 6, 1);
con.restore();
con.save();
//大刻度
setDial(con, 0, 100, 0, 1);
for (var i = 1; i < 12; i++)
setDial(con, 0, 100, 30, 3);
con.restore();
con.save();
//表针
setTimeHand(con);
}, 1);
</script>