本来是只想写个时钟的,但是我不太会读这个钟,所以写了个js返回当前时间。
主要是实现了两个部分的功能:
第一部分,用js编写showTime返回时间,很简单,用Date相关的get方法实现。
第二部分,用canvas+js画个简单的时钟。
功能展示
代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
padding: 0;
margin: 0;
}
canvas {
display: block;
margin: 100px auto;
}
h1{
text-align: center;
color: hotpink;
}
</style>
</head>
<body>
<div id="time"></div>
<script>
function showTime(){
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate();
var hour=date.getHours();
var minute=date.getMinutes();
var second=date.getSeconds();
var element=document.getElementById('time');
element.innerHTML='<h1>'+year+'-'+month+'-'+day+'-'+hour+':'+minute+':'+second;
}
window.onload=function(){
setInterval('showTime()',1000);
}
</script>
<canvas id="clock" width="300" height="300"></canvas>
<!-- 时钟 -->
<script>
init();
function init() {
let canvas = document.querySelector("#clock");
let ctx = canvas.getContext("2d");
draw(ctx);
}
function draw(ctx) {
requestAnimationFrame(function step() {
drawDial(ctx);
drawAllHands(ctx);
requestAnimationFrame(step);
});
}
function drawAllHands(ctx) {
let time =new Date();
// 获取时间
let s = time.getSeconds();
let m = time.getMinutes();
let h = time.getHours();
let pi = Math.PI;
// 计算弧度
let secondAngle = pi / 180 * 6 * s;
let minuteAngle = pi / 180 * 6 * m + secondAngle / 60;
let hourAngle = pi / 180 * 30 * h + minuteAngle / 12;
drawHands(hourAngle, 60, 6, "pink", ctx);
drawHands(minuteAngle, 106, 4, "orange", ctx);
drawHands(secondAngle, 129, 2, "skyblue", ctx);
}
function drawHands(angle, len, width, color, ctx) {
ctx.save();
ctx.translate(150, 150);
ctx.rotate(-Math.PI / 2 + angle);
ctx.beginPath();
ctx.moveTo(-4, 0);
ctx.lineTo(len, 0);
ctx.lineWidth = width;
ctx.strokeStyle = color;
ctx.lineCap = "round";
ctx.stroke();
ctx.closePath();
ctx.restore();
}
function drawDial(ctx) {
let pi = Math.PI;
ctx.clearRect(0, 0, 300, 300);
ctx.save();
ctx.translate(150, 150);
ctx.beginPath();
ctx.arc(0, 0, 148, 0, 2 * pi);
ctx.strokeStyle= 'orange';
ctx.stroke();
ctx.closePath();
for (let i = 0; i < 60; i++) {
ctx.save();
ctx.rotate(-pi / 2 + i * pi / 30);
ctx.beginPath();
ctx.moveTo(110, 0);
ctx.lineTo(140, 0);
ctx.lineWidth = i % 5 ? 2 : 4;
ctx.strokeStyle=i%5?"skyblue":"purple";
ctx.stroke();
ctx.closePath();
ctx.restore();
}
ctx.restore();
}
</script>
</body>
</html>