<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> canvas { border: 1px solid red; } </style> </head>
<body> <canvas width="400" height="400"></canvas> <script> const canvas = document.querySelector("canvas"); const clock = canvas.getContext("2d");
const W = canvas.offsetWidth;//获取当前canvas的宽 const H = canvas.offsetHeight;//获取当前canvas的高
let arr = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];//生成一个数组 const pi = Math.PI; //表盘部分 function biaopan() { //外边的圆 clock.save(); clock.translate(200, 200); clock.beginPath(); clock.arc(0, 0, 200, 0, 2 * pi); clock.fill(); clock.stroke(); //里边的圆 clock.beginPath(); clock.arc(0, 0, 180, 0, 2 * pi); clock.strokeStyle = "red"; clock.fillStyle="white" clock.fill(); clock.stroke();
clock.beginPath(); clock.arc(0, 0, 2, 0, 2 * pi); clock.stroke(); //小时数的刻针 clock.beginPath(); for (let i = 0; i < 12; i++) { clock.beginPath(); clock.moveTo(0, -180); clock.lineTo(0, -150); clock.stroke(); clock.rotate(pi / 6); }
//生成60个小刻针 clock.beginPath(); for (let i = 0; i < 60; i++) { clock.beginPath(); clock.moveTo(0, -180); clock.lineTo(0, -175); clock.strokeStyle = "red"; clock.stroke(); clock.rotate(2 * pi / 60); } //表盘生成数字 for (let i = 0; i < arr.length; i++) { clock.beginPath(); clock.moveTo(0, -180); clock.fillText(arr[i],0,-180) clock.strokeStyle = "red"; clock.stroke(); clock.rotate(2 * pi / 12); }
};
//时针部分 function Dhour(hour) { clock.save(); clock.beginPath(); let rod = 2 * pi / 12 * hour; clock.rotate(rod); clock.lineWidth = "6";
clock.moveTo(0, 0); clock.lineTo(0, -70); clock.strokeStyle = "black"; clock.stroke(); clock.restore();
}
//分钟 function DMinutes(minute) { clock.save(); clock.beginPath(); let rod = 2 * pi / 60 * minute; clock.rotate(rod); clock.moveTo(0, 0); clock.lineTo(0, -100); clock.strokeStyle = "bule"; clock.stroke(); clock.restore(); } //秒针的部分 function DSeconds(second) { clock.save(); clock.beginPath(); let rod = 2 * pi / 60 * second; clock.rotate(rod); clock.moveTo(0, 0); clock.lineTo(0, -160); clock.strokeStyle = "green"; clock.stroke(); clock.restore(); }
function Draw() { clock.restore(); clock.clearRect(0, 0, H, W) let date = new Date(); let hours = date.getHours(); let minutes = date.getMinutes(); let seconds = date.getSeconds(); biaopan(); Dhour(hours); DMinutes(minutes); DSeconds(seconds); } //时间函数执行前 先执行一次 Draw(); setInterval(Draw, 1000)
</script> </body>
</html>