HTML5 Canvas简易时钟
2011 3 4 08:18 PM 4837次查看
分类:JavaScript 标签:HTML, JavaScript
由于各种浏览器对文本的处理有些差异,因此我就只管Chrome了,用其他浏览器的自己看着办吧…
所用的方法很简单,就是用context对象的arc方法画3个同心圆弧,然后每秒递增一定量的弧度。
需要注意的是每画一条圆弧都要调用beginPath方法,不然2条圆弧会自动连接起来,而closePath方法不是必须的。
最后代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Canvas时钟</title>
</head>
<body>
<canvas id="canvas" width="200" height="200">你的浏览器不支持canvas元素,请更换更先进的浏览器。</canvas>
<script>
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.lineWidth = 8;
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
ctx.shadowBlur = 2;
ctx.font = '16px monospace';
var startAngle = -Math.PI / 2;
function drawClock() {
var time = new Date();
var hours = time.getHours();
var am = true;
if (hours >= 12) {
hours -= 12;
am = false;
}
var minutes = time.getMinutes();
var seconds = time.getSeconds();
ctx.clearRect(0, 0, 200, 200);
ctx.beginPath();
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.shadowColor = "rgba(255, 128, 128, 0.5)";
ctx.arc(100, 100, 90, startAngle, (hours / 6 + minutes / 360 + seconds / 21600 - 0.5) * Math.PI, false);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = "rgb(0, 255, 0)";
ctx.shadowColor = "rgba(128, 255, 128, 0.5)";
ctx.arc(100, 100, 75,startAngle, (minutes / 30 + seconds / 1800 - 0.5) * Math.PI, false);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = "rgb(0, 0, 255)";
ctx.shadowColor = "rgba(128, 128, 255, 0.5)";
ctx.arc(100, 100, 60,startAngle, (seconds / 30 - 0.5) * Math.PI, false);
ctx.stroke();
time = [];
if (hours < 10) {
time.push('0');
}
time.push(hours);
time.push(':');
if (minutes < 10) {
time.push('0');
}
time.push(minutes);
time.push(':');
if (seconds < 10) {
time.push('0');
}
time.push(seconds);
if (am) {
time.push('AM');
} else {
time.push('PM');
}
ctx.fillText(time.join(''), 50, 105);
}
drawClock();
setInterval(drawClock, 1000);
}
</script>
</body>
</html>
向下滚动可载入更多评论,或者点这里禁止自动加载。