canvas圆形时钟效果

2018-7-16 22:51| 作者: admin| 查看: 715| 评论: 0|来自: 蚂蚁部落

本章节分享一段代码实例,它利用canvas实现了圆形时钟效果。

代码实例如下:

[HTML] 纯文本查看 复制代码运行代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
</head>
<body>
<canvas id="clock" width="500" height="500"></canvas>
<script>
var clock = document.getElementById('clock');
var cxt = clock.getContext('2d');
 
function drawClock() {
  //获取时间
  cxt.clearRect(0, 0, 500, 500);
  var now = new Date();
  var sec = now.getSeconds();
  var min = now.getMinutes();
  var hour = now.getHours();
  //规格化
  hour = hour + min / 60;
  hour = hour > 12 ? hour - 12 : hour;
 
  //表盘
  cxt.lineWidth = 10;
  cxt.strokeStyle = "blue";
  cxt.beginPath();
  cxt.arc(250, 250, 200, 0, 360, false);
  cxt.closePath();
  cxt.stroke();
  //表盘格
  for (var i = 0; i < 12; i++) {
    cxt.save();
    cxt.lineWidth = 7;
    cxt.strokeStyle = "#000";
    cxt.translate(250, 250);
    cxt.rotate(i * 30 * Math.PI / 180);
    cxt.beginPath();
    cxt.moveTo(0, -170);
    cxt.lineTo(0, -190);
    cxt.closePath();
    cxt.stroke();
    cxt.restore();
  }
 
  for (var i = 0; i < 60; i++) {
    cxt.save();
    cxt.lineWidth = 5;
    cxt.strokeStyle = "#000";
    cxt.translate(250, 250);
    cxt.rotate(i * 6 * Math.PI / 180);
    cxt.beginPath();
    cxt.moveTo(0, -180);
    cxt.lineTo(0, -190);
    cxt.closePath();
    cxt.stroke();
    cxt.restore();
  }
 
  //时针
  cxt.save();
  cxt.lineWidth = 7;
  cxt.strokeStyle = "#000";
  cxt.translate(250, 250);
  cxt.rotate(hour * 30 * Math.PI / 180);
  cxt.beginPath();
  cxt.moveTo(0, -140);
  cxt.lineTo(0, 10);
  cxt.closePath();
  cxt.stroke();
  cxt.restore();
 
 
  //分针
  cxt.save();
  cxt.lineWidth = 5;
  cxt.strokeStyle = "#000";
  cxt.translate(250, 250);
  cxt.rotate(min * 6 * Math.PI / 180);
  cxt.beginPath();
  cxt.moveTo(0, -160);
  cxt.lineTo(0, 15);
  cxt.closePath();
  cxt.stroke();
  cxt.restore();
 
 
  //秒针
  cxt.save();
  cxt.strokeStyle = "red";
  cxt.lineWidth = 3;
  cxt.translate(250, 250);
  cxt.rotate(sec * 6 * Math.PI / 180);
  cxt.beginPath();
  cxt.moveTo(0, -170);
  cxt.lineTo(0, 20);
  cxt.closePath();
  cxt.stroke();
  cxt.beginPath();
  cxt.arc(0, 0, 5, 0, 360, false);
  cxt.closePath();
  cxt.fillStyle = "gray";
  cxt.fill();
  cxt.stroke();
  cxt.beginPath();
  cxt.arc(0, -150, 5, 0, 360, false);
  cxt.closePath();
  cxt.fillStyle = "gray";
  cxt.fill();
  cxt.stroke();
 
  cxt.restore();
}
drawClock();
setInterval(drawClock, 1000);
</script>
</body>
</html>

鲜花

握手

雷人

路过

鸡蛋

最新评论

返回顶部