基于html5 canvas的一个日期时间控件、日期选择器
时间: 2023-08-11 07:06:04 浏览: 51
下面是一个基于 HTML5 Canvas 的日期时间控件/日期选择器的示例代码,你可以根据自己的需求进行修改和优化:
```html
<!DOCTYPE html>
<html>
<head>
<title>Date Time Picker using HTML5 Canvas</title>
<style type="text/css">
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function drawClock() {
var now = new Date();
var sec = now.getSeconds();
var min = now.getMinutes();
var hr = now.getHours();
// Draw clock face
ctx.beginPath();
ctx.arc(canvas.width/2, canvas.height/2, 100, 0, 2*Math.PI);
ctx.fillStyle = '#fff';
ctx.fill();
ctx.lineWidth = 10;
ctx.strokeStyle = '#333';
ctx.stroke();
// Draw hour marks
ctx.lineWidth = 5;
for (var i = 0; i < 12; i++) {
var angle = (i - 3) * (Math.PI * 2) / 12;
ctx.beginPath();
var x1 = canvas.width/2 + Math.cos(angle) * 80;
var y1 = canvas.height/2 + Math.sin(angle) * 80;
var x2 = canvas.width/2 + Math.cos(angle) * 70;
var y2 = canvas.height/2 + Math.sin(angle) * 70;
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
// Draw minute marks
ctx.lineWidth = 2;
for (var i = 0; i < 60; i++) {
var angle = (i - 3) * (Math.PI * 2) / 60;
ctx.beginPath();
var x1 = canvas.width/2 + Math.cos(angle) * 80;
var y1 = canvas.height/2 + Math.sin(angle) * 80;
var x2 = canvas.width/2 + Math.cos(angle) * 75;
var y2 = canvas.height/2 + Math.sin(angle) * 75;
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
// Draw hour hand
ctx.lineWidth = 14;
var angle = (hr - 3) * (Math.PI * 2) / 12;
ctx.beginPath();
ctx.moveTo(canvas.width/2, canvas.height/2);
ctx.lineTo(canvas.width/2 + Math.cos(angle) * 50, canvas.height/2 + Math.sin(angle) * 50);
ctx.stroke();
// Draw minute hand
ctx.lineWidth = 10;
var angle = (min - 15) * (Math.PI * 2) / 60;
ctx.beginPath();
ctx.moveTo(canvas.width/2, canvas.height/2);
ctx.lineTo(canvas.width/2 + Math.cos(angle) * 70, canvas.height/2 + Math.sin(angle) * 70);
ctx.stroke();
// Draw second hand
ctx.lineWidth = 6;
var angle = (sec - 15) * (Math.PI * 2) / 60;
ctx.beginPath();
ctx.moveTo(canvas.width/2, canvas.height/2);
ctx.lineTo(canvas.width/2 + Math.cos(angle) * 90, canvas.height/2 + Math.sin(angle) * 90);
ctx.stroke();
// Draw center
ctx.beginPath();
ctx.arc(canvas.width/2, canvas.height/2, 5, 0, 2*Math.PI);
ctx.fillStyle = '#333';
ctx.fill();
}
setInterval(drawClock, 1000);
</script>
</body>
</html>
```
这个示例代码中使用 canvas 绘制了一个时钟,你可以根据需要将它转换为日期时间控件/日期选择器。