在网页上显示一个钟表


<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JavaScript教程</title>

<script>

function startTime()

{

  var today=new Date();

  var h=today.getHours();

  var m=today.getMinutes();

  var s=today.getSeconds();

  m=checkTime(m);

  s=checkTime(s);

  var time=document.getElementById('txt');

  time.innerHTML=h+":"+m+":"+s;

  t=setTimeout('startTime()',500);

}

function checkTime(i)

{

  if(i<10)

  { i="0"+i; }

  return i;

}

</script>

</head>

<body οnlοad="startTime()">

<div id="txt"></div>

</body>

</html>

效果截图如下:

 

转载于:https://www.cnblogs.com/Knowledge-wealth/p/5788098.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是实现该功能的代码: ``` <html> <head> <script> function drawClock() { var canvas = document.getElementById("clock"); var ctx = canvas.getContext("2d"); var radius = canvas.height / 2; ctx.beginPath(); ctx.arc(radius, radius, radius-10, 0, 2*Math.PI); ctx.fillStyle = "white"; ctx.fill(); ctx.lineWidth = 5; ctx.stroke(); ctx.beginPath(); ctx.arc(radius, radius, 10, 0, 2*Math.PI); ctx.fillStyle = "black"; ctx.fill(); var now = new Date(); var hour = now.getHours(); var minute = now.getMinutes(); var second = now.getSeconds(); // Draw hour hand ctx.lineWidth = 7; ctx.strokeStyle = "black"; ctx.beginPath(); var angle = Math.PI / 6 * hour + Math.PI / 360 * minute; var x = radius + (radius-40) * Math.cos(angle); var y = radius + (radius-40) * Math.sin(angle); ctx.moveTo(radius, radius); ctx.lineTo(x, y); ctx.stroke(); // Draw minute hand ctx.lineWidth = 5; ctx.strokeStyle = "black"; ctx.beginPath(); angle = Math.PI / 30 * minute + Math.PI / 1800 * second; x = radius + (radius-20) * Math.cos(angle); y = radius + (radius-20) * Math.sin(angle); ctx.moveTo(radius, radius); ctx.lineTo(x, y); ctx.stroke(); // Draw second hand ctx.lineWidth = 3; ctx.strokeStyle = "red"; ctx.beginPath(); angle = Math.PI / 30 * second; x = radius + (radius-10) * Math.cos(angle); y = radius + (radius-10) * Math.sin(angle); ctx.moveTo(radius, radius); ctx.lineTo(x, y); ctx.stroke(); setTimeout(drawClock, 1000); } window.onload = function() { drawClock(); } </script> </head> <body> <canvas id="clock" width="200" height="200"></canvas> </body> </html> ``` 解释一下代码: - 首先创建一个 `canvas` 元素,并给它一个 `id` 为 `clock`。 - 在 `window.onload` 事件中调用 `drawClock` 函数,以便在页面加载完毕后开始绘制钟表。 - `drawClock` 函数主要分为以下几个部分: - 通过 `document.getElementById` 获取 `canvas` 元素以及上下文对象 `ctx`。 - 计算钟表半径 `radius`。 - 绘制钟表的外圆和中心点。 - 获取当前时间,并计算时、分、秒对应的角度。 - 绘制时针、分针、秒针。其中时针的角度需要加上分钟的偏移量,分针的角度需要加上秒钟的偏移量。 - 调用 `setTimeout` 函数,每隔一秒钟重新绘制钟表。 注意,为了减少 CPU 的占用率,这里使用了 `setTimeout` 函数的轮询方式来重复绘制钟表。如果需要更加精确地显示时间,可以使用 `requestAnimationFrame` 函数来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值