HTML5・アナログ時計




ソースコード

html5clock.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML5・アナログ時計</title>
<script>
var cvs; // canvas要素のオブジェクトを取得
var cnt; // コンテキストを取得
var today,h,m,s,rad;

window.onload = function(){
  setInterval("draw()",1000);
}

var update = function(){
  today=new Date();
  h=today.getHours();
  m=today.getMinutes();
  s=today.getSeconds();
}

var draw = function(){
  update();
  cvs = document.getElementById("clock");
  cnt = cvs.getContext("2d");

  cnt.beginPath();
  cnt.fillStyle = "#000000";
  cnt.arc(100, 100, 100, 0, Math.PI*2, true);
  cnt.fill();

  cnt.beginPath();
  cnt.fillStyle = "#ffffff";
  cnt.arc(100, 100, 90, 0, Math.PI*2, true);
  cnt.fill();
  
  // 秒針
  rad = Math.PI/2 - s * Math.PI * 2 / 60
  var sx = 100 + 80 * Math.cos(rad);
  var sy = 100 - 80 * Math.sin(rad);
  cnt.beginPath();
  cnt.moveTo(100,100);
  cnt.lineTo(sx,sy);
  cnt.strokeWidth = 1;
  cnt.strokeStyle = "#000000";
  cnt.stroke();
  
  // 長針
  rad = Math.PI/2 - m * Math.PI * 2 / 60 - s * Math.PI * 2 / 3600
  var mx = 100 + 60 * Math.cos(rad);
  var my = 100 - 60 * Math.sin(rad);
  cnt.beginPath();
  cnt.moveTo(100,100);
  cnt.lineTo(mx,my);
  cnt.strokeWidth = 3;
  cnt.strokeStyle = "#0000ff";
  cnt.stroke();

  // 短針
  rad = Math.PI/2 - h * Math.PI * 2 / 12 - m * Math.PI * 2 / 720 - s * Math.PI * 2 / 43200
  var hx = 100 + 40 * Math.cos(rad);
  var hy = 100 - 40 * Math.sin(rad);
  cnt.beginPath();
  cnt.moveTo(100,100);
  cnt.lineTo(hx,hy);
  cnt.strokeWidth = 5;
  cnt.strokeStyle = "#ff0000";
  cnt.stroke();
}
</script>
</head>
<body bgcolor="#c0c0c0" style="margin-left:auto;margin-right:auto;text-align:center;">
<h1>HTML5・アナログ時計</h1>
<canvas id="clock" width="200" height="200">
</canvas>
</body>
</html>



Shadow Academy トップへ戻る

inserted by FC2 system