
##表盘
1.初始化
将圆心调整到画布的中间
由于canvas中画圆与旋转所参照的坐标系于正常坐标系有出入
将整个画布逆时针旋转90度
初始化一些样式数据
ctx.lineWidth = 8;
ctx.strokeStyle = "black";
ctx.lineCap = "round";
2.外层空心圆盘
圆盘颜色:#325FA2
圆盘宽度:14
圆盘半径:140
3.时针刻度
长度为20
宽度为8
外层空心圆盘与时针刻度之间的距离也为20
4.分针刻度
宽度为4
长度为3
5.时针
宽度为14
圆心外溢出80 收20
6.分针
宽度为10
圆心外溢出112 收28
7.秒针
颜色:D40000
宽度为6
圆心外溢出83 收30
---->中心实心圆盘
半径为10
---->秒针头
96码开外半径为10的空心圆
宽度为6
绘制钟表:
demo地址:https://github.com/Hightinstance/practice/blob/master/Clocks/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
html,body{
height: 100%;
overflow: hidden;
background: pink;
}
#clock{
background: gray;
position: absolute;
left: 50%;
top: 50%;
transform: translate3d(-50%,-50%,0);
}
</style>
</head>
<body>
<canvas id="clock" width="400" height="400"></canvas>
</body>
<script type="text/javascript">
window.onload = function(){
//画表盘
var clock = document.querySelector("#clock");
if(clock.getContext)
{
var ctx = clock.getContext("2d");
move();
setInterval(function(){
//每次清除画布
ctx.clearRect(0,0,clock.width,clock.height);
move();
},1000);
}
function move(){
//外圈
ctx.save();
//钟表样式
ctx.lineWidth = 8;
ctx.strokeStyle = "black";
ctx.lineCap = "round";
//中心点的坐标和坐标系转换
ctx.translate(200,200);
ctx.rotate(-90*Math.PI/180);
ctx.beginPath();
//画圆
ctx.save();//存储外部表盘的样式
ctx.strokeStyle = "#325FA2";
ctx.lineWidth = 14;
ctx.beginPath();
ctx.arc(0,0,140,0,360);
ctx.stroke();
ctx.restore();
//时针
// 长度为20
// 宽度为8
// 外层空心圆盘与时针刻度之间的距离也为20,画12个,旋转30度
ctx.save();
//相同的样式不需要清除
for(var i=0;i<12;i++)
{
ctx.lineWidth = 8;
ctx.beginPath();
ctx.moveTo(100,0);
ctx.lineTo(120,0);
ctx.stroke();
ctx.rotate(30*Math.PI/180);
}
ctx.restore();
//分针同样的套路
ctx.save();
//相同的样式不需要清除
for(var i=0;i<60;i++)
{
ctx.lineWidth = 4;
ctx.beginPath();
ctx.moveTo(117,0);
ctx.lineTo(120,0);
ctx.stroke();
ctx.rotate(6*Math.PI/180);
}
ctx.restore();
var date = new Date();
var s = date.getSeconds();
var m = date.getMinutes()+s/60;
var h = date.getHours()+m/60;
//12小时制
h=h>12?h-12:h;
//画分针,时针,秒针,
//时针
ctx.save();
ctx.lineWidth = 14;
ctx.rotate(h*30*Math.PI/180);
ctx.beginPath();
ctx.moveTo(-20,0);
ctx.lineTo(80,0);
ctx.stroke();
ctx.restore();
//分针
ctx.save();
ctx.lineWidth = 10;
ctx.rotate(m*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(-28,0);
ctx.lineTo(112,0);
ctx.stroke();
ctx.restore();
//秒针
ctx.save();
ctx.lineWidth = 6;
ctx.strokeStyle = "#D40000";
ctx.fillStyle = "#D40000";
ctx.rotate(s*6*Math.PI/180);
ctx.beginPath();
ctx.moveTo(-30,0);
ctx.lineTo(83,0);
ctx.stroke();
//中心圆
ctx.beginPath();
ctx.arc(0,0,10,0,360);
ctx.fill();
//表头
ctx.beginPath();
ctx.arc(96,0,10,0,360);
ctx.stroke();
//秒针清空样式
ctx.restore();
//最后清空,坐标系和原点需要使用
ctx.restore();
}
}
</script>
</html>
原文:https://www.cnblogs.com/love-life-insist/p/9136598.html