<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>钟表</title>
<style>
body{
background: url("http://img5.imgtn.bdimg.com/it/u=4232091053,186747754&fm=26&gp=0.jpg");
}
#clock-box{
position:absolute;
width:300px;
height:300px;
left: calc(50% - 150px);
top:50%;
margin-top: -150px;
border:3px solid #000;
border-radius: 30%;
background: url("http://img3.imgtn.bdimg.com/it/u=380617583,3455526712&fm=26&gp=0.jpg");
}
#clock{
position: relative;
left:calc(50% - 125px);
top:6px;
}
ul{
list-style: none;
position:relative;
font-size: 20px;
}
//伪类的使用
li:first-child{
position:absolute;
left:140px;
top:-20px;
width:10px;
height:10px;
}
li:nth-child(2){
position:absolute;
width:10px;
height:10px;
top:120px;
right: 10px;
}
li:nth-child(3){
position:absolute;
width:10px;
height:10px;
top:120px;
left: 10px;
}
li:nth-child(4){
position:absolute;
left:140px;
top:250px;
width:10px;
height:10px;
}
</style>
</head>
<body>
<div id="clock-box">
<ul>
<li>12</li>
<li>3</li>
<li>6</li>
<li>9</li>
</ul>
<canvas id="clock" width="250" height="250"></canvas>
</div>
</body>
<script>
let clock_canvas=document.querySelector("#clock");
let ctx=clock_canvas.getContext("2d");
var getTime=(type)=>{
var date = new Date();
if(Object.is(type, '秒针')){
let second = date.getSeconds();
let s_angle=(second/60)*2*Math.PI;
ctx.lineTo((120+125*Math.sin(s_angle)),(120-125*Math.cos(s_angle)));
}else if(Object.is(type, '分针')){
let minute = date.getMinutes();
let m_angle=(minute/60)*2*Math.PI;
ctx.lineTo((120+90*Math.sin(m_angle)),(120-90*Math.cos(m_angle)));
}else{
let hour = date.getHours();
let minute = date.getMinutes();
let h_angle=((hour-12)/12+(1/12)*(minute/60))*2*Math.PI;
ctx.lineTo((120+60*Math.sin(h_angle)),(120-60*Math.cos(h_angle)));
}
};
let Draw=()=>{
//清空画布
ctx.clearRect(0,0,clock_canvas.width,clock_canvas.height);
//绘制秒针
ctx.beginPath();
ctx.strokeStyle="#f00";
ctx.moveTo(120,120);
getTime('秒针');
ctx.lineWidth=2;
ctx.closePath();
ctx.stroke();
//绘制分针
ctx.beginPath();
ctx.strokeStyle="#000";
ctx.moveTo(120,120);
getTime('分针');
ctx.lineWidth=4;
ctx.closePath();
ctx.stroke();
//绘制时针
ctx.beginPath();
ctx.strokeStyle="#000";
ctx.moveTo(120,120);
getTime('时针');
ctx.lineWidth=5;
ctx.closePath();
ctx.stroke();
//绘制表盘中心点
ctx.beginPath();
ctx.fillStyle="#00f";
ctx.arc(120,120,8,0,2*Math.PI);
ctx.closePath();
ctx.fill();
}
var timer=setInterval(Draw,100);
</script>
</html>
网友评论