html5 畫布繪製時鐘
用Html5實現時鐘,包括轉盤時鐘和電子時鐘,顯示當前日期時間
繪製步驟:
(1)先獲取畫布,設定畫布的大小;
(2)在js中獲取畫布物件,獲取畫布的畫筆物件,設定畫筆的一些屬性;
(3)獲取系統當前時間,轉換成時分秒,用變數儲存下來;
(4)先畫分鐘刻度線,每6°畫一條線,共60條刻度線(迴圈);
(5)畫時鐘刻度線,每30°畫一條線,相對分針長一點粗一點,共12條線
(6)畫時針、分針和秒針,時針最短最粗,秒針最細最長,根據當前時間把時針,分針,秒針旋轉到相應位置;
(7)接著繪製數字時鐘,根據當前的時間在畫布上繪製文字,顯示時間日期(年月日)星期幾;
(8)呼叫函式,並設定定時器定時執行函式,實現動態效果。
效果圖:
原始碼:
<!DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title>時鐘</title>
<style type="text/css">
canvas{
margin: 100px 80px;
}
</style>
</head>
<body>
<canvas id="clock"width="1000" height="200"></canvas>
<scripttype="text/javascript">
var canvas =document.querySelector("canvas");
canvas.style.background ="blue";
var g = canvas.getContext("2d");
//繪製轉盤時鐘
function drawArcClock() {
g.clearRect(0, 0, 100, 100);
var data = new Date();
var sec = data.getSeconds();
var min = data.getMinutes();
var hour = data.getHours();
g.save();
g.translate(50, 50);
g.rotate(-Math.PI / 2);
//分鐘刻度線
for(var i = 0; i < 60; i++) {//畫60個刻度線
g.beginPath();
g.strokeStyle ="white";
g.lineWidth = 1;
g.moveTo(50, 0);
g.lineTo(45, 0);
g.stroke();
g.rotate(Math.PI / 30); //每個6deg畫一個時鐘刻度線
g.closePath();
}
//時鐘刻度線
for(var i = 0; i < 12; i++) {//畫12個刻度線
g.beginPath();
g.strokeStyle ="white";
g.lineWidth = 2;
g.moveTo(50, 0);
g.lineTo(40, 0);
g.stroke();
g.rotate(Math.PI / 6); //每個30deg畫一個時鐘刻度線
g.closePath();
}
//畫時針
hour = hour > 12 ? hour - 12 :hour;
g.beginPath();
g.save();
g.rotate(Math.PI / 6 * hour +Math.PI / 6 * min / 60 + Math.PI / 6 * sec / 3600);
g.strokeStyle = "white";
g.lineWidth = 3;
g.moveTo(-10, 0);
g.lineTo(30, 0);
g.stroke();
g.restore();
g.closePath();
//畫分針
g.beginPath();
g.save();
g.rotate(Math.PI / 30 * min +Math.PI / 30 * sec / 60);
g.strokeStyle = "white";
g.lineWidth = 2;
g.moveTo(-5, 0);
g.lineTo(30, 0);
g.stroke();
g.restore();
g.closePath();
//畫秒針
g.beginPath();
g.save();
g.rotate(Math.PI / 30 * sec);
g.strokeStyle = "red";
g.lineWidth = 1;
g.moveTo(-10, 0);
g.lineTo(35, 0);
g.stroke();
g.restore();
g.closePath();
g.restore();
}
//繪製數字時鐘
function drawNumClock(){
g.clearRect(100, 0, 1200, 200);
var data = new Date();
var str = data.getFullYear()+"年"+(data.getMonth()+1)+"月"+data.getDate()+"日";
var sec = data.getSeconds();
var min = data.getMinutes();
var hour = data.getHours();
var day =data.getDay(); //獲取當前星期
if(day == 0){
day = "日";
}
else if(day==1){
day = "一";
}
else if(day==2){
day = "二";
}
else if(day==3){
day = "三";
}
else if(day==4){
day = "四";
}
else if(day==5){
day = "五";
}
else if(day==6){
day = "六";
}
g.fillStyle = "white";
g.font = "100px '楷體'";
g.lineWidth = "bolder";//字型加粗
g.beginPath();
g.fillText(hour,200,120);
g.fillText(":",300,110);
g.fillText(min,340,120);
g.font = "70px '楷體'";
g.fillText(sec,470,120);
g.font = "70px '楷體'";
g.fillText("星期",580,120);
g.fillText(day,730,120);
g.font = "50px '楷體'";
g.fillText(str,580,180);
}
drawArcClock();
drawNumClock();
setInterval(drawArcClock, 1000);
setInterval(drawNumClock, 1000);
</script>
</body>
</html>