<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id='draw' width="200" height="200">A draw canvas</canvas>
<script>
let draw = document.getElementById('draw');
let context = draw.getContext('2d');
let angle = Math.PI/360;
var DateTime = {
initDial: function(){
context.save();
context.beginPath();
context.arc(100, 100, 99, 0, 2*Math.PI, false);
context.moveTo(194, 100);
context.arc(100, 100, 94, 0, 2*Math.PI ,false);
//移動座標原點,便於計算
context.translate(100,100);
context.moveTo(0,0);
context.font = 'bold 14px Arial';
context.textAlign = 'center';
context.textBaseline = 'middle';
//確定時刻的位置,根據相對的sin、cos、指針半徑長度角度定
let cos60 = Math.cos(2*angle*60)*85;
let cos30 = Math.cos(2*angle*30)*85;
let sin60 = Math.sin(2*angle*60)*85;
let sin30 = Math.sin(2*angle*30)*85;
context.fillText('12', 0, -85);
context.fillText('1', cos60, -sin60);
context.fillText('2', cos30, -sin30);
context.fillText('3', 85, 0);
context.fillText('4', cos30, sin30);
context.fillText('5', cos60, sin60);
context.fillText('6', 0, 85);
context.fillText('7',-cos60, sin60);
context.fillText('8',-cos30, sin30);
context.fillText('9', -85, 0);
context.fillText('10', -cos30, -sin30);
context.fillText('11', -cos60, -sin60);
context.strokeStyle = '#4DB3FF';
context.stroke();
context.restore();
},
initmin: function(){
let min = new Date().getMinutes();
// console.log(min);
context.save();
context.beginPath();
context.translate(100,100);
context.moveTo(0,0);
context.rotate(2 * Math.PI / 60 * min);
// context.rotate(Math.PI/2);
context.lineTo(0,-85);
context.lineWidth = 2;
context.stroke();
context.restore();
},
inithour : function (){
let hour = new Date().getHours();
let min = new Date().getMinutes();
context.save();
context.beginPath();
hour = hour>12 ? hour-12 : hour;
context.translate(100,100)
context.moveTo(0,0);
//小時的弧度加上時間的偏移量
context.rotate(2 * Math.PI / 12*hour + 2 * Math.PI /60 *min /12);
context.lineTo(0, -65);
context.lineWidth = 3;
context.lineCap = 'round';
context.stroke();
context.restore();
},
initsec : function(){
let sec = new Date().getSeconds();
context.save();
// console.log(sec);
context.beginPath();
//移動座標原點
context.translate(100,100)
context.rotate(2 * Math.PI / 60*sec);
context.moveTo(-2, 0);
context.lineTo(2,0);
context.lineTo(1,-90);
context.lineTo(-1,-90);
context.fillStyle = 'red';
context.fill();
context.restore();
}
}
function autotime(){
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
DateTime.initDial();
DateTime.inithour();
DateTime.initmin();
DateTime.initsec();
clearTimeout(t);
var t = setTimeout(function(){
autotime()
},1000)
}
autotime();
</script>
</body>
</html>
canvs繪製動態時鐘
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.