canvas时钟程序终于写完了,在计算那些角度换算时,说明学好数学真的很重要,没有良好的逻辑思路理解的有点蛋疼!想当年我数学是那么溜,现在却,咳咳好汉不提当年勇。
花了半天吧canvas基本时钟程序都理解了,并且自己加了一个小美观的分钟点函数。js代码如下:
/**
* Created by Administrator on 2015/4/22.
*/
var canvas = document.getElementById("mycanvas");
context = canvas.getContext("2d");
FONT_HEIGHT = 15;
MARGIN = 35;
HAND_TRUNCATION = canvas.width/25;
HOUR_HAND_TRUNCATION = canvas.width/10;
NUMERAL_SPACING = 20;
RADIUS = canvas.width/2 - MARGIN;
HAND_RADIUS = RADIUS + NUMERAL_SPACING;
//绘制圆形
function drawCircle(){
context.beginPath();
context.arc(canvas.width/2,canvas.height/2,RADIUS,0,Math.PI*2,true);
context.strokeStyle = 'black';
context.stroke();
}
//绘制边缘的各个时间数字
function drawNumberals(){
var numerals = [1,2,3,4,5,6,7,8,9,10,11,12];
angle = 0;
var i = 0;
numeralsWidth=0;
numerals.forEach(function(numeral){
angle = Math.PI/6 * (numeral-3);
numeralsWidth = context.measureText(numeral).width;
context.fillText(numeral,canvas.width/2+Math.cos(angle)*(HAND_RADIUS)-numeralsWidth/2,canvas.height/2+Math.sin(angle)*(HAND_RADIUS)+FONT_HEIGHT/3);
});
}
//绘制每一分钟的断点
function drawMin(){
angle=0;
longer =0;
for(i=0;i<60;i++){
if(i%5==0){
longer = RADIUS*18/20;
}else{
longer = RADIUS*19/20;
}
angle = Math.PI/30*i;
context.moveTo(canvas.width/2+Math.cos(angle)*longer,canvas.height/2-Math.sin(angle)*longer);
context.lineTo(canvas.width/2+Math.cos(angle)*RADIUS,canvas.height/2-Math.sin(angle)*RADIUS);
context.strokeStyle = 'black'
context.stroke();
}
}
//绘制时针的中心点
function drawCenter(){
context.beginPath();
context.arc(canvas.width/2,canvas.height/2,2,0,Math.PI*2,true);
context.fill()
}
//根据给的参数绘制指针
function drawHander(loc,isHour){
var angle = (Math.PI*2)*(loc/60)-Math.PI/2;
context.beginPath();
if(isHour){
handRadius = RADIUS - HOUR_HAND_TRUNCATION-HAND_TRUNCATION ;
}else{
handRadius = 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.strokeStyle = 'black'
context.stroke();
}
//获取参数,传递指针参数,获取指针
function drawHandels(){
var date = new Date();
hour = date.getHours();
hour = hour>12?hour-12:hour;
drawHander((hour+(date.getMinutes()/60))*5,true);//时针
drawHander(date.getMinutes(),false);//分针
drawHander(date.getSeconds(),false);//秒针
}
function drawClock(){
context.clearRect(0,0,canvas.width,canvas.height)
drawCircle();
drawCenter();
drawMin();
drawNumberals();
drawHandels()
}
context.font=FONT_HEIGHT +'px,Arial';
loop = setInterval(drawClock,1000);
html代码如下
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>一个基本的时钟程序</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#mycanvas{
background-color: burlywood;
}
body{
background-color: cornflowerblue;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="200" height="200">
your brower is not support!
</canvas>
<script src="一个基本时钟程序.js" ></script>
</body>
</html>