加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
index.html 2.99 KB
一键复制 编辑 原始数据 按行查看 历史
虫鱼水兽 提交于 2016-05-28 21:58 . js时钟源码 基于html canvas
<html>
<head>
<title></title>
</head>
<body>
<canvas width=500 height=500 id="clockCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("clockCanvas"),
ctx = canvas.getContext("2d"),
CENTER_POINT = {
x:250,
y:250,
radius:100,
startAngle:0,endAngle:Math.PI*2},
TIME_NUMBER = [1,2,3,4,5,6,7,8,9,10,11,12];
function drawCircle(){
// ctx.moveTo(CENTER_POINT.x,
// CENTER_POINT.y);
ctx.beginPath();
ctx.strokeStyle="black";
ctx.arc(CENTER_POINT.x,
CENTER_POINT.y,CENTER_POINT.radius,CENTER_POINT.startAngle
,CENTER_POINT.endAngle,true);
ctx.stroke();
};
//画数字
function drawNumber(){
ctx.beginPath();
ctx.strokeStyle="black";
var angle = 2*Math.PI/TIME_NUMBER.length;
ctx.font = "20px Microsoft YaHei";
for(var i=1;i<=TIME_NUMBER.length;i++){
var y = CENTER_POINT.y-Math.cos(angle*i)*(CENTER_POINT.radius-10)+7,
x = CENTER_POINT.x+Math.sin(angle*i)*(CENTER_POINT.radius-10)-7;
ctx.strokeText(i,x,y);
}
ctx.stroke();
};
// ctx.stroke();
var arrowRadius = CENTER_POINT.radius-40,
arrowAngle = Math.PI*2/60,time=0,
last = null;
function clearRect(){
ctx.clearRect(CENTER_POINT.x-CENTER_POINT.radius,CENTER_POINT.y-CENTER_POINT.radius,CENTER_POINT.radius*2,CENTER_POINT.radius*2);
}
var hourRadius = CENTER_POINT.radius-50,
hourAngle = Math.PI*2/(60*12);
function drawHour(date){
/*if(time>60){
time = 0;
}*/
ctx.beginPath();
var hour = ((date.getHours()%12)*60)+date.getMinutes();
console.log(date.getHours()*60+" "+date.getMinutes());
ctx.moveTo(CENTER_POINT.x,CENTER_POINT.y);
var y = CENTER_POINT.y-Math.cos(hourAngle*hour)*hourRadius,
x = CENTER_POINT.x+Math.sin(hourAngle*hour)*hourRadius;
ctx.lineTo(x,y);
ctx.stroke();
// last = {x:x,y:y};
time++;
}
function drawTime(date){
ctx.beginPath();
ctx.strokeStyle = "blue";
// if(time>60){
// time = 0;
// }
var time = date.getMinutes();
ctx.moveTo(CENTER_POINT.x,CENTER_POINT.y);
var y = CENTER_POINT.y-Math.cos(arrowAngle*time)*arrowRadius,
x = CENTER_POINT.x+Math.sin(arrowAngle*time)*arrowRadius;
ctx.lineTo(x,y);
ctx.stroke();
// last = {x:x,y:y};
time++;
}
var secondRadius = arrowRadius+20;
function drawSeconds(date){
ctx.beginPath();
ctx.strokeStyle = 'red';
// if(time>60){
// time = 0;
// }
var time = date.getSeconds();
ctx.moveTo(CENTER_POINT.x,CENTER_POINT.y);
var y = CENTER_POINT.y-Math.cos(arrowAngle*time)*secondRadius,
x = CENTER_POINT.x+Math.sin(arrowAngle*time)*secondRadius;
ctx.lineTo(x,y);
ctx.stroke();
// last = {x:x,y:y};
time++;
}
function startClock(){
var date = new Date();
console.log(date);
clearRect();
ctx.beginPath();
drawCircle();
drawNumber();
drawHour(date);
drawTime(date);
drawSeconds(date);
ctx.stroke();
}
startClock();
window.onload = function(){
setInterval(function(){
startClock();
},1000);
}
</script>
</body>
</html>
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化