canvas 时钟案例

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#c{
background:#ccc;
}
</style>
</head>
<body>
<canvas id="c" width="400" height="400"></canvas>
</body>
</html>
<script>
var cd=document.getElementById("c");
var c=cd.getContext("2d");

c.save();
c.arc(200,200,100,0,2*Math.PI);
c.stroke();
c.restore();


//绘制秒盘
c.save();
c.translate(200,200);
c.beginPath();
for(var i=0;i<60;i++){
c.moveTo(95,0);
c.lineTo(100,0);
c.rotate(6*Math.PI/180);
}
c.closePath();
c.stroke();
c.restore();

//绘制时盘

c.save();
c.translate(200,200);
c.beginPath();
for(var i=0;i<12;i++){
c.moveTo(90,0);
c.lineTo(100,0);
c.rotate(30*Math.PI/180);
}
c.closePath();
c.stroke();
c.restore();


fn();

function fn() {

var time, h, m, s;
time = new Date();
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
h = h - 12;
//时针;
c.save();
c.beginPath();
c.lineWidth = "3";
c.lineCap = "round";
c.moveTo(200, 200);
c.arc(200, 200, 50, (-90 + h * 30+(m/2)) * Math.PI / 180, (-90 + h * 30+(m/2)) * Math.PI / 180);
c.closePath();
c.stroke();
c.restore();

//分针
c.save();
c.beginPath();
c.lineWidth = "1";
c.lineCap = "round";
c.moveTo(200, 200);
c.arc(200, 200, 62, (-90 + m * 6) * Math.PI / 180, (-90 + m * 6) * Math.PI / 180);
c.closePath();
c.stroke();
c.restore();

// 秒针

c.save();
c.beginPath();
c.moveTo(200, 200);
c.arc(200, 200, 62, (-90 + s * 6) * Math.PI / 180, (-90 + s * 6) * Math.PI / 180);
c.closePath();
c.stroke();
c.restore();
}

var tsd=setInterval(function(){
c.save();
c.clearRect(130,130,140,140);
fn();
c.restore();
},1000)
</script>
原文地址:https://www.cnblogs.com/shangjun6/p/10894612.html