以下是一個通過canvas寫的時鐘小練習
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
/*清除瀏覽器的默認效果*/
*{
margin: 0;
padding: 0;
}
html body{
height: 100%;
overflow:hidden ;
background: pink;
}
#clock{
background: white;
position: absolute;
left: 50%;
top: 50%;
transform: translate3d(-50%,-50%,0);
}
</style>
</head>
<body>
<canvas id="clock" width="400" height="400"></canvas>
<script type="text/javascript">
window.onload = function(){
var clock =document.querySelector("#clock")
if(clock.getContext){
var ctx = clock.getContext("2d")
//設置定時器,每一秒調用一次, 調用時清除上一次的畫布
setInterval(function(){
ctx.clearRect(0,0,clock.width,clock.height)
move()
},1000)
move()
function move (){
ctx.save()
ctx.lineWidth = 8
ctx.strokeStyle = "black"
//調整座標軸
ctx.translate(200,200) //移動畫布的座標軸
ctx.rotate(-90*Math.PI/180) //將畫布的座標軸逆時針旋轉90度
ctx.beginPath()
//外層空心圓盤
ctx.save();
ctx.strokeStyle = "#325FA2"
ctx.lineWidth = 14
ctx.beginPath()
ctx.arc(0,0,140,0,360*Math.PI/180)
ctx.stroke()
ctx.restore()
//時針刻度
ctx.save()
ctx.beginPath()
for(var i =0;i <12;i++){ //時針的刻度有12個 每個刻度之間是30度
ctx.rotate(30*Math.PI/180)
ctx.moveTo(120,0)
ctx.lineTo(100,0)
ctx.stroke()
}
ctx.restore()
//分針刻度
ctx.save()
ctx.lineWidth = 4
ctx.beginPath()
for(var i =0;i <60;i++){
if(i%5!=0){ //分針刻度之間的角度是6度 但是爲了提高效率 當i是五的倍數是 跳過
ctx.moveTo(120,0)
ctx.lineTo(117,0)
ctx.stroke()
}
ctx.rotate(6*Math.PI/180)
}
ctx.restore()
//時針 分針 秒針 表座
var date = new Date(); //獲取系統當前的時間
var s = date.getSeconds(); //秒
var m = date.getMinutes()+s/60; //分
var h =date.getHours()+m/60 //時
h = h>12?h-12 :h //默認h是0-24 轉換成0-12
//時針
ctx.save()
ctx.lineWidth =14
ctx.rotate(h*30*Math.PI/180)
ctx.beginPath()
ctx.moveTo(-20,0)
ctx.lineTo(80,0)
ctx.stroke()
ctx.restore()
//分針
ctx.save()
ctx.lineWidth =10
ctx.rotate(m*6*Math.PI/180)
ctx.beginPath()
ctx.moveTo(-28,0)
ctx.lineTo(112,0)
ctx.stroke()
ctx.restore()
//秒針
ctx.save()
ctx.strokeStyle ="#D40000"
ctx.fillStyle = "#D40000"
ctx.lineWidth =6
ctx.rotate(s*6*Math.PI/180)
ctx.beginPath()
ctx.moveTo(-30,0)
ctx.lineTo(83,0)
ctx.stroke()
//表座
ctx.beginPath()
ctx.arc(0,0,10,0,360*Math.PI/180)
ctx.fill()
//秒頭
ctx.beginPath()
ctx.arc(96,0,10,0,360*Math.PI/180)
ctx.stroke()
ctx.restore()
ctx.restore()
}
}
}
</script>
</body>
</html>
顯示的效果如下
如果發現錯誤請及時留言,有不懂的也可以留言,我會及時解答!!!!