时钟绘制的非常简易,但该有的都有了。
效果图如下,
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>clock</title>
<style>
body{
background: #ddd;
}
#canvas {
margin: 10px;
padding: 10px;
background: #fff;
border: thin inset #aaa;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script src="Example2-1.js"></script>
</body>
</html>
HTML代码
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var FONT_HEIGHT = 15;
var MARGIN = 35;
var HAND_TRUNCATION = canvas.width/25;
var HOUR_HAND_TRUNCATION = canvas.width/10;
var NUMERAL_SPACING = 20;
var RADIUS = canvas.width/2 - MARGIN;
var HAND_RADIUS = RADIUS + NUMERAL_SPACING; //绘制圆形
function drawCircle(){
context.beginPath();
context.arc(canvas.width/2,canvas.height/2,RADIUS,0,Math.PI*2,true);
//(圆心x坐标,圆心y坐标,半径,起点角,终点角,绘制方向(顺/逆))
context.stroke();
} //绘制时刻数字
function drawNumberals(){
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/15)- Math.PI/2,
handRadius = isHour ? RADIUS -HAND_TRUNCATION -HOUR_HAND_TRUNCATION : RADIUS -HAND_TRUNCATION;
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);
drawHand(date.getMinutes(),false);
drawHand(date.getSeconds(),false);
} function drawClock(){
context.clearRect(0,0,canvas.width,canvas.height); //清空画布 drawCircle();
drawCenter();
drawHands();
drawNumberals()
} //初始化
context.font = FONT_HEIGHT + 'px Arial';
loop = setInterval(drawClock,1000); //1s刷新一次
JS代码