Open wuxianqiang opened 4 years ago
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> * { margin: 0; padding: 0; } .my-svg-path { transform: rotateZ(90deg); transform-origin: 50% 50%; transition: stroke-dashoffset 2s ease; stroke-dashoffset: -260; } .text { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; } </style> </head> <body> <div id="container"> <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path d="M 50 50 m -40 0 a 40 40 0 1 0 80 0 a 40 40 0 1 0 -80 0" fill="none" stroke="#e5e9f2" stroke-width="5" ></path> <path d="M 50 50 m -40 0 a 40 40 0 1 0 80 0 a 40 40 0 1 0 -80 0" fill="none" stroke="#40a0ff" stroke-linecap="round" stroke-dasharray="260" stroke-width="5" stroke-dashoffset="-260" class="my-svg-path" id="bar" ></path> <foreignObject x="0" y="0" width="100" height="100"> <div xmlns="http://www.w3.org/1999/xhtml" class="text" id="text">50%</div> </foreignObject> </svg> <button id="btn">点击到100%</button> </div> <script> let c = Math.floor(2 * 3.24 * 40); let bar = document.getElementById('bar') let text = document.getElementById('text') function calculate (precent) { // 根据百分比计算周长 let value = -((1 - precent) * c) // 把value重新设置到troke-dashoffset属性就可以了 bar.style.strokeDashoffset = value // 更新显示的文字 text.innerHTML = `${precent * 100}%` } calculate(0.5) let btn = document.getElementById('btn') btn.onclick = function () { calculate(1) } </script> </body> </html>