用canvas实现一个钟表的功能,效果如下图:
<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<title></title>
</head>
<body>
<canvasid="myCanvas" width="1000" height="1000"></canvas>
</body>
<scripttype="text/javascript">
varmyCavans = document.querySelector("#myCanvas");
varcontext = myCanvas.getContext('2d');
functionclock() {
context.clearRect(0,0, 1000, 1000);
//获取当前的时间
varnow = new Date();
varsec = now.getSeconds();
varminute = now.getMinutes();
varhour = now.getHours();
hour= hour + minute / 60;
//表盘
varrGrd = context.createRadialGradient(200,200, 30, 200,200, 150);
rGrd.addColorStop(0, '#00ffff');
rGrd.addColorStop(1, '#0000ff');
context.fillStyle= rGrd;
context.fillRect(50,50, 300, 300);
// 表盘的原形边
context.beginPath();
context.lineWidth=2
context.strokeStyle= "white";
context.arc(200,200, 150, 0,2 * Math.PI, false);
context.fill();
context.stroke();
//大刻度
for(vari = 0; i < 12; i++) {
context.save();
context.lineWidth= 5;
context.strokeStyle= "white";
context.translate(200,200);
context.rotate(30* i * Math.PI / 180);
context.beginPath();
context.moveTo(0,-150);
context.lineTo(0,-140);
context.stroke();
context.restore();
}
//小刻度
for(vari = 0; i < 60; i++) {
context.save();
context.lineWidth= 2;
context.strokeStyle= "white";
context.translate(200,200);
context.rotate(6* i * Math.PI / 180);
context.beginPath();
context.moveTo(0,-150);
context.lineTo(0,-140);
context.stroke();
context.restore();
}
//数字
vardeg = 2 *Math.PI / 12;
context.save();
context.beginPath();
context.translate(200,200);
for(vari = 1; i < 13; i++) {
varx1 = Math.sin(i * deg);
vary1 = -Math.cos(i * deg);
context.fillStyle= "#fff";
context.font= "bold 20px Calibri";
context.textAlign= 'center';
context.textBaseline= 'middle';
context.fillText(i, x1* 120, y1 * 120);
}
context.closePath();
context.restore();
//秒针
context.save();
context.beginPath();
context.lineWidth= 2;
context.lineCap= "round";
context.strokeStyle= "red";
context.translate(200,200);
context.rotate(sec* 6 * Math.PI/ 180);
context.moveTo(0,-140);
context.lineTo(0,10);
context.stroke();
context.restore();
//分针
context.save();
context.beginPath();
context.lineWidth= 4;
context.lineCap= "round";
context.translate(200,200)
context.rotate(minute* 6 * Math.PI/ 180)
context.strokeStyle= "white";
context.moveTo(0,-120);
context.lineTo(0,10);
context.stroke();
context.restore();
//时针
context.save();
context.beginPath();
context.lineWidth= 6;
context.lineCap= "round";
context.translate(200,200)
context.rotate(hour* 30 * Math.PI/ 180)
context.strokeStyle= "black";
context.moveTo(0,-90);
context.lineTo(0,10);
context.stroke();
context.restore();
}
setInterval(clock,1000);
</script>
</html>