<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
//页面加载完运行
window.onload = function() {
var canvas=document.querySelector('canvas');
//设置画布为2d
var ctx = canvas.getContext("2d");
//调用方法
dClock();
// rgb颜色随机数
var RandomColor = function(){
var color='rgb(';
for(var i=0;i<3;i++)
{
color+=parseInt(Math.random()*256)+',';
}
color=color.slice(0,-1)+')';
return color;
}
// 声明渐变对象
var a=ctx.createLinearGradient(0,0,200,300);
a.addColorStop(0,RandomColor());
a.addColorStop(0.2,RandomColor());
a.addColorStop(0.4,RandomColor());
a.addColorStop(0.6,RandomColor());
a.addColorStop(0.8,RandomColor());
a.addColorStop(1,RandomColor());
function dClock() {
//外表盘开始路径
ctx.beginPath();
//线条宽度
ctx.lineWidth = 2;
//圆的路径,x坐标,y坐标,半径,开始弧度,结束弧度
ctx.arc(250, 250, 200, 0, Math.PI*2);
//渐变对象赋值给填充样式
ctx.fillStyle=a;
//绘制
ctx.fill();
//将开始点和结束点相连
ctx.closePath();
//圆心圆
ctx.beginPath();
//指针圆的路径,x坐标,y坐标,半径,开始弧度,结束弧度
ctx.arc(250, 250, 8, 0, 360);
//绘制
ctx.fillStyle='black';
ctx.fill();
//绘制刻度(时刻度)
//将表盘分成12格
for(var i = 0; i < 12; i++) {
//保存画笔设置
ctx.save();
// 更改线宽
ctx.lineWidth=5;
//开始路径
ctx.beginPath();
//转换坐标(使此时的坐标系原点更改为圆心坐标)
ctx.translate(250, 250);
//设置旋转角度
ctx.rotate(i *(Math.PI/6));
//画笔移至到指定位置
ctx.moveTo(0, 180);
//画笔结束位置
ctx.lineTo(0, 200);
//绘制
ctx.stroke();
//将开始位置和结束位置相连
ctx.closePath();
// 旋转数字
ctx.rotate(Math.PI/6);
// 调节大小
ctx.font='16px bold';
// 填充数字
ctx.fillText(i+1,-10,-160);
//将绘图状态置为保存值
ctx.restore();
}
//绘制刻度(分刻度) (方法同时刻度)
for(var i = 0; i < 60; i++) {
ctx.save();
ctx.beginPath();
ctx.translate(250, 250);
ctx.rotate(i *(Math.PI/6));
ctx.moveTo(0, 190);
ctx.lineTo(0, 200);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
//获取系统时间
var nowTime = new Date();
//获取当前小时
var hours = nowTime.getHours();
//获取当前分钟
var minutes = nowTime.getMinutes();
//获取秒
var seconds = nowTime.getSeconds();
//将24小时转为12小时
hours = hours > 12 ? hours - 12 : hours;
hours = hours + minutes / 60;
//保存画笔设置
ctx.save();
/*绘制时针*/
ctx.beginPath();
//画笔宽度
ctx.lineWidth =8;
//转换画布的用户坐标系统
ctx.translate(250, 250);
//将当前时间嫁接到画笔上
ctx.rotate(hours * 30 * Math.PI / 180);
//画笔开始位置
ctx.moveTo(0, 10);
//画笔结束位置
ctx.lineTo(0, -70);
//绘画
ctx.stroke();
//将开始位置和结束位置相连
ctx.closePath();
//将绘图状态置为保存值
ctx.restore();
/*绘制分针*/
ctx.save();
ctx.beginPath();
ctx.lineWidth = 4;
ctx.translate(250, 250);
ctx.rotate(minutes * 6 * Math.PI / 180);
ctx.moveTo(0, 10);
ctx.lineTo(0, -110);
ctx.stroke();
ctx.closePath();
ctx.restore();
/*绘制秒针*/
ctx.save();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.translate(250, 250);
ctx.rotate(seconds * 6 * Math.PI / 180);
ctx.moveTo(0, 10);
ctx.lineTo(0, -136);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
//设置成1秒中刷新一次
setInterval(dClock, 1000);
}
</script>
</head>
<body>
<canvas width="500px" height="500px" style="background-color: black;"></canvas>
</body>
</html>
效果图: