先来看一下效果图
屏幕快照 2017-12-26 下午9.40.41.png
下面是代码 哈哈哈
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>时钟</title>
<style type="text/css">
#clock{
/border: 1px solid black;/
display: block;
margin: 50px auto;
}
</style>
</head>
<body>
<canvas id="clock" width="300" height="300"></canvas>
</body>
<script>
var clock = document.getElementById("clock");
var context = clock.getContext("2d");
// 获取当前日期
var date = new Date();
// 获取秒
var sounds =date.getSeconds();
// 获取分钟
var minutes =date.getMinutes()+sounds/60;
// 获取小时
var hours =date.getHours()+minutes/60;
if(hours>12){
hours-=12;
}
draw(hours,minutes,sounds);
setInterval(function(){
context.translate(-150,-150);
context.clearRect(0,0,300,300);
// 获取当前日期
var date = new Date();
// 获取秒
var sounds =date.getSeconds();
// 获取分钟
var minutes =date.getMinutes()+sounds/60;
// 获取小时
var hours =date.getHours()+minutes/60;
if(hours>12){
hours-=12;
}
draw(hours,minutes,sounds);
},900);
function draw(hours,minutes,sounds){
//背景圆盘
context.beginPath();
context.fillStyle = "black";
context.arc(150,150,150,0,Math.PI2,false);
context.fill();
context.lineCap = "round"; //线帽
//改变坐标原点
context.translate(150,150);
context.rotate(Math.PI-0.5);
//时针
context.rotate(Math.PI/6hours);
context.beginPath();
context.moveTo(0,0);
context.lineWidth = 12;
context.strokeStyle = "red";
context.lineTo(50,0);
context.stroke();
context.rotate(-Math.PI/6hours);
//分针
context.rotate(Math.PI/30minutes);
context.beginPath();
context.moveTo(0,0);
context.lineWidth =6;
context.strokeStyle = "green";
context.lineTo(80,0);
context.stroke();
context.rotate(-Math.PI/30minutes);
//秒针
context.rotate(Math.PI/30sounds);
context.beginPath();
context.moveTo(0,0);
context.lineWidth =3;
context.strokeStyle = "blueviolet";
context.lineTo(100,0);
context.stroke();
context.rotate(-Math.PI/30sounds);
context.rotate(-Math.PI-0.5);
//分 和秒的刻度
for(var i=0;i<60;i++){
context.rotate(Math.PI/30);
context.beginPath();
context.moveTo(0,-130);
context.lineWidth = 1;
context.strokeStyle = "red";
context.lineTo(0,-145);
context.stroke();
}
//时刻度
for(var i=0;i<12;i++){
context.beginPath();
context.moveTo(0,-130);
context.lineWidth = 10;
context.strokeStyle = "#fff";
context.lineTo(0,-150);
context.stroke();
context.rotate(Math.PI/6);
}
//中心的圆点
context.beginPath();
context.fillStyle = "yellow";
context.arc(0,0,10,0,Math.PI2,false);
context.fill();
}
</script>
</html>
网友评论