1.效果图
其实这是一个实时动态的效果,由于我不知道怎么在markdown编辑器中插入这种动态效果,有的说做成gif动图,我嫌麻烦就懒的搞。
2.clock.html
<canvas id="myCanvas"> 您的浏览器不支持canvas,请升级! </canvas>
3.clock.css
canvas { display: block; margin: 0 auto; background: #ccc; } </style>
4.clock.js
<script> // 获取元素 var canvasNode = document.querySelector("#myCanvas"); //设置宽高 canvasNode.width = 800; canvasNode.height = 600; // 获取画笔 var ctx = canvasNode.getContext('2d'); ctx.lineWidth = 8; ctx.strokeStyle = "#000"; ctx.lineCap = "round"; //先调用一次 避免等1s后才看到效果 runWatch(); // 定时器 setInterval(runWatch,1000); // 钟表运行 function runWatch () { // 清空画布 ctx.clearRect(0,0,canvasNode.width,canvasNode.height); // 保存绘图上下文 ctx.save(); // 把圆心调到画布的中间 ctx.translate(canvasNode.width / 2,canvasNode.height / 2); // 坐标调整 x轴指向上方 ctx.rotate(-90 / 180*Math.PI); //绘制圆盘 ctx.save(); ctx.beginPath(); ctx.arc(0,0,140,0,360 / 180 * Math.PI); ctx.lineWidth = 14; ctx.strokeStyle = "#325FA2"; ctx.stroke(); ctx.restore(); // 绘制时针刻度 ctx.save(); for(var i =0;i<12;i++){ ctx.rotate(30 / 180 * Math.PI); ctx.beginPath(); ctx.moveTo(100,0); ctx.lineTo(120,0); ctx.lineWidth = 8; ctx.stroke(); } ctx.restore(); // 绘制分针刻度 ctx.save(); for (var i =0;i < 60;i++) { ctx.rotate(6 / 180 * Math.PI); ctx.beginPath(); ctx.moveTo(117,0); ctx.lineTo(120,0); ctx.lineWidth = 4; ctx.stroke(); } ctx.restore(); // 计算当前时间 var date = new Date(); // 当前秒数 var s = date.getSeconds(); // 当前分钟数 var m = date.getMinutes() + s / 60; // 当前小时数 var h = date.getHours() + m / 60; // 绘制时针 ctx.save(); ctx.rotate(h*30 / 180 * Math.PI); ctx.beginPath(); ctx.moveTo(-20,0); ctx.lineTo(80,0); ctx.lineWidth = 14; ctx.stroke(); ctx.restore(); // 绘制分针 ctx.save(); ctx.rotate(6*m / 180 * Math.PI); ctx.beginPath(); ctx.moveTo(-28,0); ctx.lineTo(112,0); ctx.lineWidth = 10; ctx.stroke(); ctx.restore(); // 绘制秒针 ctx.save(); ctx.rotate(6*s / 180 * Math.PI); // 秒针 ctx.beginPath(); ctx.moveTo(-30,0); ctx.lineTo(83,0); ctx.lineWidth = 6; ctx.strokeStyle = "#D40000"; ctx.stroke(); // 中心实心圆盘 ctx.beginPath(); ctx.arc(0,0,10,0,Math.PI*2); ctx.fillStyle = "#D40000"; ctx.fill(); // 秒针头部 空心圆盘 ctx.beginPath(); ctx.arc(96,0,10,0,Math.PI*2); ctx.stroke(); ctx.restore(); //恢复绘图上下文 ctx.restore(); } </script>
5.注意
+ canvas是行内元素。+ ctx.save();和ctx.restore();这两个方法要配合使用。
