<meta charset="utf-8"> <canvas width="1000" height="1000" id="clockCanvas" style="border:1px solid red;"> 您的浏览器版本太低,不支持显示时钟的canvas标签 </canvas> <script> var clockID = document.getElementById("clockCanvas"); var clock = clockID.getContext("2d"); function drawClock(id){ //*每次清空画布(在给定矩形内清空一个矩形:) clock.clearRect(0,0,1000,1000); //获取系统当前时间(时 、分 、秒) var now = new Date(); var sec = now.getSeconds(); var mins = now.getMinutes(); var hours = now.getHours(); //绘制文字,显示系统当前时间: clock.save(); //*保存之前状态 clock.translate(0,500); //*更换原点(0,0)位置为(0,500) clock.fillStyle = "#f00"; clock.strokeStyle = "#eee"; clock.font = "bold 20px 微软雅黑"; clock.strokeText("系统当前时间为:" +hours+"时" +mins+"分" +sec+"秒", 100, 100); clock.fillText("系统当前时间为:" +hours+"时" +mins+"分" +sec+"秒", 100, 100); //*在画布上输出的文本及位置 clock.restore(); //计算:满60分加一小时 hours = hours + mins/60; //计算:将24小时制转化为12小时制 hours = hours>12?hours-12:hours; //1.画表盘 clock.beginPath(); clock.lineWidth = 10; clock.strokeStyle = "#ff00ff"; clock.arc(300, 300, 200, 0, 360, false); clock.stroke(); clock.closePath(); //2.画刻度盘 //2.1 时刻度 for(var i = 0; i < 12; i++){ clock.save(); //将起始点定位到圆心 clock.translate(300,300); //设置刻度的样式 clock.lineWidth = 7; clock.strokeStyle = "#999999"; //设置旋转角度 clock.rotate(i*30*Math.PI/180); clock.beginPath(); clock.moveTo(0, -170); clock.lineTo(0, -190); clock.font = "normal 20px impack"; clock.textAlign = "left"; clock.textBaseLine = "top"; clock.strokeText(i, i*(-50)*Math.PI/180, -150); clock.closePath(); //画刻度线 clock.stroke(); clock.restore(); } //2.2 分刻度 for(var j = 0; j<60; j++){ clock.save(); //设置起始点坐标 clock.translate(300,300); clock.lineWidth = 5; clock.strokeStyle = "#999999"; //设置旋转角度 clock.rotate(j*6*Math.PI/180); clock.beginPath(); clock.moveTo(0, -180); clock.lineTo(0, -190); clock.closePath(); clock.stroke(); clock.restore(); } //3.1 时针 clock.save(); clock.translate(300,300); clock.lineWidth = 7; clock.strokeStyle = "#000000"; //设置小时的旋转角度,没转一次走30° clock.rotate(hours*30*Math.PI/180); clock.beginPath(); clock.moveTo(0,15); clock.lineTo(0,-120); clock.stroke(); clock.closePath(); clock.restore(); //3.2 分针 clock.save(); clock.translate(300, 300); clock.rotate(mins*6*Math.PI/180); clock.lineWidth = 5; clock.strokeStyle = "#000"; clock.beginPath(); clock.moveTo(0,20); clock.lineTo(0,-160); clock.stroke(); clock.closePath(); clock.restore(); //3.3 秒针 clock.save(); clock.translate(300,300); clock.rotate(sec*6*Math.PI/180); clock.lineWidth = 3; clock.strokeStyle = "#f00"; clock.beginPath(); clock.moveTo(0, 25); clock.lineTo(0,-165); clock.stroke(); clock.closePath(); //3.3.1 秒针圆心处一个小圈 clock.fillStyle = "#999"; clock.strokeStyle = "#f00"; clock.beginPath(); clock.arc(0,0,6,0,360,false); clock.fill(); clock.stroke(); clock.closePath(); //3.秒针顶部一个小圈 clock.beginPath(); clock.arc(0,-140,6,0,360,false); clock.fill(); clock.stroke(); clock.closePath(); clock.restore(); }; drawClock(); setInterval(drawClock,1000); </script>