JavaScript 实现圆钟

来源:互联网 发布:建筑施工安全网络平台 编辑:程序博客网 时间:2024/04/30 13:04
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JavaScript 时钟</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>


<body onload="showTime()">
  <canvas id="drawing" width="320" height="240"> Your browser does not support the canvas element.</canvas>
</body>


<script type="text/javascript">
function currentClock(){
var dt = new Date();
var ctx = document.getElementById("drawing").getContext("2d");
ctx.save();
ctx.clearRect(0,0,300,300);  // clear canvas
ctx.translate(150, 150);   //转换画布的用户坐标系统。  添加画布的偏移量
ctx.scale(0.5,0.5); //标注画布的用户坐标系统。  画布当前矩阵的缩放因子。

/** 添加绘制文字 **/
ctx.font = "bold 20px Arial";
ctx.fillStyle = "#D40000";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Js时钟", 0, -60);
ctx.stroke();


ctx.rotate(-Math.PI/2);//旋转画布
ctx.strokeStyle = "black";
ctx.fillStyle = "white";
ctx.lineWidth = 8;
ctx.lineCap = "round";
ctx.stroke();

//小时刻度
ctx.save();
for(var i=0; i < 12; i++){
ctx.beginPath();
//Math.PI/6  为弧度,即由角度转换弧度,由Math.PI/180。大指针之间为30度,故再乘30.
ctx.rotate(Math.PI/6);   
ctx.moveTo(100, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.restore();
//分钟刻度
ctx.save();
ctx.lineWidth = 5;
for(var i=0; i < 60; i++){
if(i%5!=0){
ctx.beginPath();
ctx.moveTo(117, 0);
ctx.lineTo(120, 0);
ctx.stroke();
}
ctx.rotate(Math.PI/30);
}
ctx.restore();


var hours = dt.getHours();
var minutes = dt.getMinutes();
var seconds = dt.getSeconds();
hours = hours > 12 ? hours - 12 : hours;

ctx.fillStyle = "black";
ctx.save();
/**
* 以小时移动弧度为基准
* Math.PI/6 为一小时所经过的弧度; Math.PI/360为一分钟,时针所经过的弧度;Math.PI/21600 为一秒钟,时针所经过的弧度
* (Math.PI/180) * 30            (Math.PI/180)*(30/360)*6              (Math.PI/180)*(30/(360*60))*6
*/
//时针指向   <!-- 以分钟移动弧度为基准 -->
ctx.rotate( (Math.PI/6) * hours + (Math.PI/360) * minutes + (Math.PI/21600) * seconds );
ctx.beginPath();
ctx.moveTo(-20, 0);
ctx.lineTo(80, 0);
ctx.stroke();
ctx.restore();

//分针指向
ctx.save();
ctx.rotate( (Math.PI/30) * minutes + (Math.PI/1800) * seconds );
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(-28, 0);
ctx.lineTo(110, 0);
ctx.stroke();
ctx.restore();

//秒针指向
ctx.save();
ctx.rotate( (Math.PI/30) * seconds );
ctx.strokeStyle = "#D40000";
ctx.fillStyle = "#D40000";
ctx.beginPath();
ctx.moveTo(-30, 0);
ctx.lineTo(83, 0);
ctx.stroke();

//添加中心圆点
ctx.beginPath();
ctx.arc(0, 0, 10, 0, Math.PI * 2, true);
ctx.fill();

/** 添加秒针尖的圆开始 **/
ctx.beginPath();
ctx.arc(95, 0, 10, 0, Math.PI * 2, true);
ctx.stroke();
ctx.fillStyle = "#555";
ctx.arc(0, 0, 1, 0, Math.PI * 2, true);
ctx.fill();
/** 添加秒针尖的圆结束 **/
ctx.restore();

// 添加最外层圆
ctx.beginPath();
ctx.lineWidth = "14";
ctx.strokeStyle = "#03515d";
ctx.arc(0, 0, 140, 0, Math.PI * 2, true);
ctx.stroke();

ctx.restore();
}


function showTime(){
currentClock();
setTimeout(showTime, 1000);
}


</script>

</html>

效果如下:

原创粉丝点击