HTML5的绝活:巧用Canvas制作会动的时钟(三)

前面的准备工作都完成了,现在我们来综合下,完成一个具有时分秒的会动的钟

  

[javascript] view plaincopy

  

$(

  function() {

  clock();

  setInterval(clock, 1000);

  }

  );

  function clock() {

  var canvas = document.getElementById("mycanvas");

  canvas.height = 500;

  canvas.width = 500;

  var context = canvas.getContext("2d");

  context.beginPath();

  context.lineWidth = 1;

  context.strokeStyle = "rgb(211,211,211)";

  for (var i = 0; i < 50; i++) {

  $.log(i);

  context.moveTo(i * 10, 0);

  context.lineTo(i * 10, 500);

  context.stroke();

  }

  for (var i = 0; i < 50; i++) {

  $.log(i);

  context.moveTo(0, i * 10);

  context.lineTo(500, i * 10);

  context.stroke();

  }

  context.beginPath();

  context.strokeStyle = "rgb(255,0,0)";

  context.arc(250, 250, 200, (Math.PI / 180) * 0, (Math.PI / 180) * 360, false);

  context.stroke();

  context.save(); //存储当前画布坐标系状态

  context.beginPath();

  context.font = "14px Tahoma"

  context.translate(255, 255); //将坐标系坐标原点移至图中间

  context.strokeStyle = "#FFFFFF";

  for (var i = 0; i < 12; i++) {

  context.fillText((i + 3) % 12 == 0 ? 12 : (i + 3) % 12, 180, 0);

  context.rotate((Math.PI / 6));

  }

  context.restore();

  context.save();

  context.beginPath();

  context.lineWidth = 5;

  context.translate(255, 255); //将坐标系坐标原点移至图中间

  for (i = 0; i < 60; i++) {

  if (i % 5 != 0) {

  context.beginPath();

  context.moveTo(180, 0);

  context.lineTo(190, 0);

  context.stroke();

  }

  context.rotate(Math.PI / 30);

  }

  context.restore();

  var now = new Date();

  var sec = now.getSeconds();

  var min = now.getMinutes();

  var hr = now.getHours() >= 12 ? now.getHours() - 12 : now.getHours();

  context.save();

  context.translate(255, 255); //将坐标系坐标原点移至图中间

  // - (Math.PI / 6) * 3 是因为0度在3点这里

  context.rotate(hr * (Math.PI / 6) + (Math.PI / 360) * min + (Math.PI / 21600) *sec - (Math.PI / 6) * 3);

  context.lineWidth = 14;

  context.beginPath();

  context.moveTo(-20, 0);

  context.lineTo(150, 0);

  context.stroke();

  context.restore();

  context.save();

  context.translate(255, 255); //将坐标系坐标原点移至图中间

  context.rotate(min * (Math.PI / 30) + (Math.PI / 1800) * sec - (Math.PI / 6) * 3)

  context.lineWidth = 10;

  context.beginPath();

  context.moveTo(-28, 0);

  context.lineTo(160, 0);

  context.stroke();

  context.restore();

  context.save();

  context.translate(255, 255); //将坐标系坐标原点移至图中间

  context.lineWidth = 1;

  context.rotate(sec * (Math.PI / 30) + (Math.PI / 1800) * sec - (Math.PI / 6) * 3)

  context.lineWidth = 10;

  context.beginPath();

  context.moveTo(-28, 0);

  context.lineTo(160, 0);

  context.stroke();

  context.restore();

  }

 

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Grow your business fast with

Suku