效果圖:
Paste_Image.png
思路:
1.設(shè)置畫(huà)布
2.利用ctx.arc繪制出大圓
3.利用for循環(huán)繪制鐘表的刻度值(小時(shí)每個(gè)刻度間隔30度竹捉,分鐘每個(gè)刻度間隔6度)萍歉,注意設(shè)置畫(huà)布的原點(diǎn)位置
4.設(shè)置時(shí)針选酗、分針、秒針
5.獲取當(dāng)期時(shí)間,并設(shè)置對(duì)應(yīng)的小時(shí)、分鐘宁否、秒的時(shí)間
6.設(shè)置指針走動(dòng):
6.1清屏
6.2重新繪制鐘表的大圓和刻度值
6.3利用ctx.rotate設(shè)置時(shí)分秒針的旋轉(zhuǎn)
另:寫(xiě)完了就發(fā)上來(lái)了,代碼沒(méi)經(jīng)過(guò)優(yōu)化缀遍,請(qǐng)各位大神諒解慕匠。
直接上代碼
html:
<canvas id="lCanvas" width="900px" height="600px"></canvas>
css:
<style type="text/css">
* {
margin: 0;
padding: 0;
list-style: none;
}
#lCanvas {
margin-left: 250px;
border: 1px solid #000;
}
</style>
javascript:
<script>
var canvas = document.getElementById("lCanvas");
//設(shè)置上下文
var ctx = canvas.getContext("2d");
//清屏
function clear() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
//鐘表刻度設(shè)置
function Scale() {
//大圓
ctx.beginPath();
ctx.arc(450, 300, 260, 0, 2 * Math.PI, false);
ctx.strokeStyle = "#FFC0CB";
ctx.lineWidth = 10;
ctx.stroke();
//刻度
var hours = 12;
var mins = 60;
for (var i = 0; i < hours; i++) {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
ctx.rotate(i * 30 * Math.PI / 180);
ctx.moveTo(-5,-190);
ctx.lineTo(5,-190)
ctx.lineWidth = 25;
ctx.stroke();
ctx.restore();
}
for (var i = 0; i < mins; i++) {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
ctx.rotate(i * 6 * Math.PI / 180);
ctx.moveTo(-2,-195);
ctx.lineTo(2,-195);
ctx.lineWidth = 10;
ctx.stroke();
ctx.restore();
}
//中心圓
ctx.save();
ctx.beginPath();
ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
ctx.arc(0, 0, 10, 0, 2 * Math.PI);
ctx.fillStyle = 'black';
ctx.fill();
ctx.restore();
}
//走動(dòng)
function timeRun() {
setInterval(function () {
//清屏
clear();
//畫(huà)時(shí)鐘
Scale();
//獲取時(shí)間
var date = new Date();
var sec= date.getSeconds();
var min = date.getMinutes() + sec / 60;
var hour = date.getHours() + min / 60;
hour = hour > 12 ? hour - 12 : hour;
//時(shí)針
ctx.save();
ctx.beginPath();
ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
ctx.rotate(hour * 30 * Math.PI / 180);
ctx.strokeStyle = '#000';
ctx.moveTo(0,-130);
ctx.lineTo(0,5);
ctx.lineWidth = 12;
ctx.stroke();
ctx.restore();
//分針
ctx.save();
ctx.beginPath();
ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
ctx.rotate(min * 6 * Math.PI / 180);
ctx.strokeStyle = '#ccc';
ctx.moveTo(0,-150);
ctx.lineTo(0,5);
ctx.lineWidth = 8;
ctx.stroke();
ctx.restore();
//秒針
ctx.save();
ctx.beginPath();
ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
ctx.rotate(sec * 6 * Math.PI / 180);
ctx.strokeStyle = 'red';
ctx.moveTo(0,-200);
ctx.lineTo(0,3);
ctx.lineWidth = 3;
ctx.stroke();
ctx.restore();
}, 1000);
}
timeRun();
</script>