1.png
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
canvas{
position: absolute;
left:10;
top:10;
}
</style>
</head>
<body>
<canvas id="dialCanvas"></canvas>
<canvas id="handCanvas"></canvas>
</body>
<script>
var dialCanvas=document.getElementById('dialCanvas');
var handCanvas=document.getElementById('handCanvas');
//定义宽度,高度和半径
var w=800;
var h=600;
var r=200;
//定义画布的大小
dialCanvas.width=w;
dialCanvas.height=h;
handCanvas.width=w;
handCanvas.height=h;
//获取画布的环境
var dialCxt=dialCanvas.getContext("2d");
var handCxt=handCanvas.getContext("2d");
//画表盘
/*
1.画表盘其实就是画圆。
2.为了数据的灵动性,数据成变量
*/
dialCxt.beginPath();
dialCxt.arc(w/2,h/2,r,0,Math.PI*2);
dialCxt.lineWidth=10;
dialCxt.strokeStyle="#000";
dialCxt.stroke();
//画刻度
//封装画刻度函数
/*
* 确定刻度上的两个点 x1,y1;x2,y2.确定内部点的时候,需要定义一个内圆
*刻度是通过画线来实现的。
*
*/
function dialScale(cxt,x,y,innerRadius,outerRadius,number=12,lineWidth=10,strokeStyle="#000"){
var angle=0;
var angleDiff= 360 / number;
for(var i=0;i<number;i++){
var x1=Math.cos(angle/180*Math.PI)*outerRadius+w/2;
var y1=Math.sin(angle/180*Math.PI)*outerRadius+h/2;
var x2=Math.cos(angle/180*Math.PI)*innerRadius+w/2;
var y2=Math.sin(angle/180*Math.PI)*innerRadius+h/2;
cxt.beginPath();
cxt.moveTo(x1,y1);
cxt.lineTo(x2,y2);
cxt.lineWidth=lineWidth;
cxt.strokeStyle=strokeStyle;
cxt.stroke();
angle=angle+angleDiff;
}
}
//调用
//画小时刻度
dialScale(dialCxt,w/2,h/2,r,r-20,12,10);
//画分钟和秒的刻度
dialScale(dialCxt,w/2,h/2,r,r-10,60,2);
//画指针
//封住画指针函数
//需要特别注意利用环境保存,不然画不了。
function drawHand(cxt,x,y,angle,length,lineWidth,strokeStyle){
cxt.save();
cxt.beginPath();
cxt.translate(x,y);
cxt.rotate((angle-90)/180*Math.PI)
cxt.moveTo(-20,0);
cxt.lineTo(length,0);
cxt.lineWidth=lineWidth;
cxt.strokeStyle=strokeStyle;
cxt.stroke();
cxt.restore();
}
//画秒针
//drawHand(dialCxt,w/2,h/2,6,180,1,"red");
//画分针
//drawHand(dialCxt,w/2,h/2,6,150,5,"#000");
//画时针
//drawHand(dialCxt,w/2,h/2,30,140,5,"#000");
//时针转动
function run(){
var date=new Date();
//清空画布
handCxt.clearRect(0,0,w,h);
var seconds=date.getSeconds();
drawHand(handCxt,w/2,h/2,6*seconds,180,1,"red");
var minutes=date.getMinutes()+seconds / 60;
drawHand(handCxt,w/2,h/2,6*minutes,150,5,"#000");
var hours=date.getHours() % 12+minutes / 60;
drawHand(handCxt,w/2,h/2,30*hours,100,5,"#ccc");
//console.log(hours);
setTimeout(run,1000);
}
run();
</script>
</html>
网友评论