<canvas id=‘clock‘ width=500 height=500> 您的浏览器需要升级 </canvas> <script type="text/javascript" charset="utf-8"> var clock=document.getElementById("clock"); var cxt=clock.getContext(‘2d‘); function drawClock () { //清除画布 cxt.clearRect(0,0,500,500); var now=new Date(); var sec=now.getSeconds(); var min=now.getMinutes(); var hour=now.getHours(); //时间格式 问题:将24小时制转化整12小时制 hour=hour>12?hour-12:hour; hour=hour+min/60; //表盘(蓝色) cxt.strokeStyle=‘blue‘; cxt.lineWidth=10; cxt.beginPath(); cxt.arc(250,250,200,0,360,false); cxt.closePath(); cxt.stroke(); //刻度 //时刻度 for (var i=0;i<12;i++) { cxt.save(); cxt.lineWidth=7; cxt.strokeStyle=‘#000‘; //设置开始点 cxt.translate(250,250); //设置弧度 cxt.rotate(i*30*Math.PI/180); cxt.beginPath(); cxt.moveTo(0,-170); cxt.lineTo(0,-190); cxt.closePath(); cxt.stroke(); cxt.restore(); } //分刻度 for (var i=0;i<60;i++) { cxt.save(); cxt.strokeStyle=‘#000‘; cxt.lineWidth=5; cxt.translate(250,250); cxt.rotate(i*6*Math.PI/180); cxt.beginPath(); cxt.moveTo(0,-180); cxt.lineTo(0,-190); cxt.closePath(); cxt.stroke(); cxt.restore(); } //时针 //设置时针分割 cxt.save(); cxt.lineWidth=7; cxt.strokeStyle=‘#000‘; cxt.translate(250,250); cxt.rotate(hour*30*Math.PI/180); cxt.beginPath(); cxt.moveTo(0,-140); cxt.lineTo(0,10); cxt.closePath(); cxt.stroke(); cxt.restore(); //分针 cxt.save(); cxt.lineWidth=5; cxt.strokeStyle=‘#000‘; cxt.translate(250,250); cxt.rotate(min*6*Math.PI/180); cxt.beginPath(); cxt.moveTo(0,-160); cxt.lineTo(0,15); cxt.closePath(); cxt.stroke(); cxt.restore(); //秒针 cxt.save(); cxt.lineWidth=3; cxt.strokeStyle=‘red‘; ///cxt.translate(250,250); cxt.translate(250,250); cxt.rotate(sec*6*Math.PI/180); cxt.beginPath(); cxt.moveTo(0,-170); cxt.lineTo(0,20); cxt.closePath(); cxt.stroke(); //秒针修饰 cxt.beginPath(); cxt.arc(0,0,5,0,360,false); cxt.closePath(); //设置填充样式 cxt.fillStyle=‘gray‘; cxt.fill(); cxt.stroke(); //画另一个小圆 cxt.beginPath(); cxt.arc(0,-150,5,0,360,false); cxt.closePath(); //设置填充样式 cxt.fillStyle=‘gray‘; cxt.fill(); cxt.stroke(); cxt.restore(); } //使用定时器让表针动起来 drawClock(); setInterval(‘drawClock()‘,1000); </script>
时间: 2024-10-11 00:43:07