在时钟的绘制中,主要用到canvas绘图API:
arc()
beginPath()
clearRect()
fill()
fillText()
lineTo()
moveTo()
stroke()
效果图如下:
页面代码如下:
<!DOCTYPE html>
<html>
<head>
<title>A Simple Canvas Example</title>
<style>
body {
background: #ddd;
}
#canvas {
margin: 10px;
padding: 10px;
background: #fff;
border: thin inset #aaa;
/* width: 600px;
height: 300px; */
}
</style>
</head>
<body>
<!-- <canvas id="canvas">
canvas not supported
</canvas> -->
<canvas id="canvas" width="600" height="600">
canvas not supported
</canvas>
<script src="clock.js"></script>
</body>
</html>
逻辑代码:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
FONT_HEIGHT = 15,
MARGIN = 35,
HAND_TRUNCTION = canvas.width/25,
HOUR_HAND_TRUNCTION = canvas.width/10,
NUMERAL_SPACING = 20,
RADIUS = canvas.width/2 - MARGIN,
HAND_RADIUS = RADIUS + NUMERAL_SPACING;
// functions....
function drawCircle() {
context.beginPath();
// var width = canvas.width >= canvas.height ? canvas.height : canvas.width
// context.arc(width/2, width/2, RADIUS, 0 , Math.PI*2, true);
context.arc(canvas.width/2, canvas.height/2, RADIUS, 0 , Math.PI*2, true);
context.stroke();
}
function drawNumerals() {
var numerals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
angle = 0,
numeralWidth = 0;
numerals.forEach(function(numeral){
angle = Math.PI/6 * (numeral - 3);
numeralWidth = context.measureText(numeral).width;
context.fillText(numeral, canvas.width/2 + Math.cos(angle)*(HAND_RADIUS) -
numeralWidth/2, canvas.height/2 + Math.sin(angle)*(HAND_RADIUS)+FONT_HEIGHT/3);
});
}
function drawCenter() {
context.beginPath();
context.arc(canvas.width/2, canvas.height/2, 5, 0, Math.PI*2, true);
context.fill();
}
function drawHand(loc, isHour) {
var angle = (Math.PI*2) * (loc/60) - Math.PI/2,
handRadius = isHour ? RADIUS - HAND_TRUNCTION - HOUR_HAND_TRUNCTION : RADIUS - HAND_TRUNCTION;
context.moveTo(canvas.width/2, canvas.height/2);
context.lineTo(canvas.width/2 + Math.cos(angle)*handRadius,canvas.height/2+Math.sin(angle)*handRadius);
context.stroke();
}
function drawHands() {
var date = new Date,
hour = date.getHours();
hour = hour > 12 ? hour - 12 : hour ;
drawHand(hour*5 + (date.getMinutes()/60)*5, true, 0.5);
drawHand(date.getMinutes(), false, 0.5);
drawHand(date.getSeconds(), false, 0.2);
}
function drawClock() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawCircle();
drawCenter();
drawHands();
drawNumerals();
}
// Initialization。。。
context.font = FONT_HEIGHT + 'px Arial';
loop = setInterval(drawClock, 1000)