SVG实现时钟效果
公旦 人气:0本文实例为大家分享了SVG实现时钟效果的具体代码,供大家参考,具体内容如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title></title> <style> * { margin: 0; } </style> </head> <body> <svg width="400" height="400"> <title>SVG Analog Clock</title> <circle id="face" cx="125" cy="125" r="100" style="fill: #f1f1f1; stroke: #000;"></circle> <g id="ticks" transform="translate(125, 125)"> <path id="triangle" d="M95 0 L 100 -5 L 100 5 Z" transform="rotate(360)"></path> </g> <g id="hands"> <path id="hour" d="M 125 125 V 75" style="fill: none; stroke: black; stroke-width: 6" transform="rotate(0)"></path> <path id="minute" d="M 125 125 V 50" style="fill: none; stroke: black; stroke-width: 4" transform="rotate(0)"></path> <path id="second" d="M 125 125 Q 100 100 125 80 T 125 40 V 30" style="fill: none; stroke: #f00; stroke-width: 2" transform="rotate(0)"></path> </g> <g id="knob" transform="translate(125, 125)"> <circle cx="0" cy="0" r="6" style="fill: #333;"></circle> </g> </svg> <script> var svgns = "http://www.w3.org/2000/svg"; var face = document.getElementById("face"), ticks = document.getElementById("ticks"), triangle = document.getElementById("triangle"), txt = document.getElementById("txt"); for (var i = 0; i < 11; i++) { var temp_triangle = triangle.cloneNode(true); var angle = i * 30 + 30; temp_triangle.setAttribute("transform", "rotate(" + angle + ")"); ticks.appendChild(temp_triangle); ticks.setAttribute("transform", "translate(125, 125), rotate(-90)"); } var hourHand = document.getElementById("hour"), minuteHand = document.getElementById("minute"), secondHand = document.getElementById("second"); var hourTransform, minuteTransform, secondTransform; var secPer12Hours = 60 * 60 * 12, secPerHour = 60 * 60, secPerMinute = 60; (function init() { hourTransform = hourHand.transform.baseVal.getItem(0); minuteTransform = minuteHand.transform.baseVal.getItem(0); secondTransform = secondHand.transform.baseVal.getItem(0); updateClock(); })() function updateClock() { var date = new Date(); var sec = date.getMilliseconds() / 1000 + date.getSeconds() + date.getMinutes() * 60 + date.getHours() * 60 * 60; var hourAngle = (sec % secPer12Hours) * 360 / secPer12Hours, minuteAngle = (sec % secPerHour) * 360 / secPerHour, secondAngle = (sec % secPerMinute) * 360 / secPerMinute; hourTransform.setRotate(hourAngle, 125, 125); minuteTransform.setRotate(minuteAngle, 125, 125); secondTransform.setRotate(secondAngle, 125, 125); window.requestAnimationFrame(updateClock); } </script> </body> </html>
浏览器需要支持:requestAnimationFrame
有关requestAnimationFrame的相关知识请自行查阅
加载全部内容