您的位置:首页 > Web前端 > HTML5

html5 时钟

2016-02-10 10:30 453 查看
<!DOCTYPE html>
<html>
<head>
<title>钟表</title>
<meta charset="utf-8">
</head>
<body>
<canvas id="mycanvas" width="500" height="500" style="border: 1px solid blue"></canvas>
<div style="margin:30px; " >Time:<input type="text"  id="time"></div>
<script type="text/javascript">
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "#FF0000";
var r = 150;
var w=200;
var h=200;
ctx.arc(w,h,r+20,0,Math.PI*2,true);
ctx.stroke();

//填充圆盘数字
for (var i = 1; i <=12; i++) {
ctx.font = "20px Arial ";
ctx.textAlign ="center";
ctx.textBaseline = "middle"; //
ctx.strokeText(i,w+Math.sin(Math.PI/6*i)*r,h-Math.cos(Math.PI/6*i)*r);

}

//画时 分 秒针

ctx.beginPath(); //画秒针
ctx.strokeStyle = "blue";
ctx.lineWidth=5;
ctx.moveTo(w,h);
ctx.lineTo(w+115,h+115);
ctx.stroke();

ctx.beginPath(); //画时针
ctx.strokeStyle = "black";
ctx.moveTo(w,h);
ctx.lineTo(w+60,h+90);
ctx.stroke();

ctx.beginPath(); //画分针
ctx.strokeStyle = "red";
ctx.moveTo(w,h);
ctx.lineTo(w+40,h+125);
ctx.stroke();

//让时钟走起来
function clock(hour,m,s) {

//第一步:先清空盘面即重新画一次表盘
ctx.beginPath();
ctx.lineWidth=2;
ctx.fillStyle = "white";
ctx.strokeStyle="red";
ctx.arc(w,h,r+20,0,Math.PI*2,true);
ctx.stroke();
ctx.fill();
ctx.font = "20px Arial ";
ctx.textAlign ="center";
ctx.textBaseline = "middle";
for (var i = 1; i <=12; i++) {
ctx.strokeText(i,w+Math.sin(Math.PI/6*i)*r,h-Math.cos(Math.PI/6*i)*r);

}

//画刻度

ctx.beginPath();
for (var i = 1; i <= 60; i++) {
if(i%5==0){
ctx.moveTo(w+Math.sin(Math.PI/30*i)*(r+8),h-Math.cos(Math.PI/30*i)*(r+8));

}else{
ctx.moveTo(w+Math.sin(Math.PI/30*i)*(r+12),h-Math.cos(Math.PI/30*i)*(r+12));

}
ctx.lineTo(w+Math.sin(Math.PI/30*i)*(r+18),h-Math.cos(Math.PI/30*i)*(r+18));
}
ctx.stroke();

//秒针走动
ctx.beginPath();
ctx.lineWidth=5;
ctx.strokeStyle = "blue";
ctx.moveTo(w,h);
ctx.lineTo(w+Math.sin(Math.PI/30*s)*(r+18),h-Math.cos(Math.PI/30*s)*(r+18));
ctx.stroke();

//分针走动
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.moveTo(w,h);
ctx.lineTo(w+Math.sin(Math.PI/30*m)*(r-6),h-Math.cos(Math.PI/30*m)*(r-6));
ctx.stroke();

//时针走动
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.moveTo(w,h);
ctx.lineTo(w+Math.sin(Math.PI/6*hour)*(r-60),h-Math.cos(Math.PI/6*hour)*(r-60));
ctx.stroke();
}

//给clock函数传递时分秒参数
function update() {

var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();

clock(hour,minute,second);

//input里面显示当前时间
var time = document.getElementById("time");
time.value = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();

}

//这里调用封装的clock函数,即update函数
var int = window.setInterval("update()",100);
</script>
</body>
</html>


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: