效果圖:
源代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>時鍾</title>
</head>
<body>
<canvas id="clock" width="500" height="500">
你的瀏覽器不支持canvas標簽,無法看到時鍾。
</canvas>
<script type="text/javascript">
var clock=document.getElementById("clock");
var cxt=clock.getContext('2d');
function drawclock(){
//清除畫布
cxt.clearRect(0,0,500,500);
var now=new Date();
var sec=now.getSeconds();
var min=now.getMinutes();
var hour=now.getHours();
hour=hour+min/60;
//將小時轉換為12小時
hour=hour>12?hour-12:hour;
//表盤
cxt.beginPath();
cxt.lineWidth=10;
cxt.strokeStyle="green";
cxt.arc(250,250,200,0,360,false);
cxt.stroke();
cxt.closePath();
//刻度
//時刻度
for(var i=0;i<12;i++){
cxt.save();
cxt.lineWidth=7;
cxt.strokeStyle="black";
cxt.translate(250,250);//設置0,0點
cxt.rotate(i*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-170);
cxt.lineTo(0,-190);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//分刻度
for( var i=0;i<60;i++){
cxt.save();
cxt.lineWidth=3;
cxt.strokeStyle="black";
cxt.translate(250,250);
cxt.rotate(i*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-180);
cxt.lineTo(0,-190);
cxt.closePath();
cxt.stroke();
cxt.restore();
}
//時針
//設置時針風格
cxt.save();
cxt.lineWidth=7;
cxt.beginPath();
cxt.strokeStyle="black";
cxt.translate(250,250);
cxt.rotate(hour*30*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-130);
cxt.lineTo(0,18);
cxt.closePath();
cxt.stroke();
cxt.restore();
//分針
cxt.save();
cxt.lineWidth=5;
cxt.beginPath();
cxt.strokeStyle="black";
cxt.translate(250,250);
cxt.rotate(min*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-150);
cxt.lineTo(0,18);
cxt.closePath();
cxt.stroke();
cxt.restore();
//秒針
cxt.save();
cxt.lineWidth=2;
cxt.beginPath();
cxt.strokeStyle="red";
cxt.translate(250,250);
cxt.rotate(sec*6*Math.PI/180);
cxt.beginPath();
cxt.moveTo(0,-163);
cxt.lineTo(0,18);
cxt.closePath();
cxt.stroke();
//畫出時針,分針,秒針交叉點
cxt.beginPath();
cxt.fillStyle="gray";
cxt.strokeStyle="red";
cxt.arc(0,0,5,0,360,false);
cxt.fill();
cxt.closePath();
cxt.stroke();
cxt.beginPath();
cxt.fillStyle="gray";
cxt.strokeStyle="red";
cxt.arc(0,-140,5,0,360,false);
cxt.fill();
cxt.closePath();
cxt.stroke();
cxt.restore();
}
drawclock();
//實驗setINterval
setInterval(drawclock,1000);
</script>
</body>
</html>
注意:在寫代碼是一定要先剖析清楚你要做什么,具有哪些步驟,先羅列好,然后一步步的實現,寫的時候每寫好一個步驟就調試一個,看效果如何。