当前位置:首页 > 自己看书写了一个最简单的时钟,后续会更新美化后的,canvas时钟效果(一)

自己看书写了一个最简单的时钟,后续会更新美化后的,canvas时钟效果(一)

发布于 2019-02-20 阅读 419 次 Canvas HTML5

代码应该还是比较容易看懂的。

初始的一些准备

  1. var canvas = document.getElementById('canvas');
  2. context = canvas.getContext('2d'),
  3. FONT_HEIGHT = 15,
  4. MARGIN = 35,
  5. HAND_TRUNCATION = canvas.width/25,
  6. HOUR_HAND_TRUNCATIO = canvas.width/10,
  7. NUMBER_SPACING = 20,
  8. RADIUS = canvas.width/2 - MARGIN,
  9. NUMBER_RADIUS = RADIUS + NUMBER_SPACING;
  10. canvas.width = 600;
  11. canvas.height = 300;
  12. context.font = FONT_HEIGHT + 'px Arial';
  13. // context.textBaseline = 'middle';

绘制表盘的外部圆形

  1. function drawCircle(){
  2. context.beginPath();
  3. context.arc(canvas.width/2, canvas.height/2, RADIUS, 0 ,Math.PI*2, true);
  4. context.stroke();
  5. }

绘制表盘数字

  1. function drawNumberals(){
  2. var numberals = [1,2,3,4,5,6,7,8,9,10,11,12],
  3. angle = 0,
  4. numberalWidth = 0;
  5. numberals.forEach(function(numberal){
  6. angle = Math.PI/6 *(numberal-3);
  7. numberalWidth = context.measureText(numberal).width;
  8. context.fillText(numberal, canvas.width/2+Math.cos(angle)*NUMBER_RADIUS-numberalWidth/2, canvas.height/2+Math.sin(angle)*NUMBER_RADIUS+FONT_HEIGHT/2);
  9. })
  10. }

绘制表盘中间的圆形点

  1. function drawCenter(){
  2. context.beginPath();
  3. context.arc(canvas.width/2, canvas.height/2, 10, 0 ,Math.PI*2, true);
  4. context.fill();
  5. }

绘制指针

  1. /**
  2. * loc Number 12小时时间
  3. * isHour Boolean 是否是时针
  4. */
  5. function drawHand(loc, isHour){
  6. var angle = Math.PI*2*loc/60 - Math.PI/2,
  7. hand_radius = isHour ? RADIUS - HAND_TRUNCATION - HOUR_HAND_TRUNCATIO : RADIUS - HAND_TRUNCATION;
  8. context.beginPath();
  9. context.moveTo(canvas.width/2, canvas.height/2);
  10. context.lineTo(canvas.width/2+Math.cos(angle)*hand_radius, canvas.height/2+Math.sin(angle)*hand_radius);
  11. context.stroke();
  12. }

绘制所有指针

  1. function drawHands(){
  2. var date = new Date(),
  3. hour = date.getHours();
  4. hour = hour > 12 ? hour - 12 : hour; //24时转12时
  5. drawHand(hour*5 + date.getMinutes()/60*5, true); //这里要注意一下,小时和分钟的转换关系
  6. drawHand(date.getMinutes(), false);
  7. drawHand(date.getSeconds(), false);
  8. }

绘制钟表

  1. function drawClock(){
  2. context.clearRect(0, 0, canvas.width, canvas.height);
  3. drawCircle();
  4. drawNumberals();
  5. drawCenter();
  6. drawHands();
  7. }

让表针动起来

  1. setInterval(drawClock, 1000);
  2. drawClock();