美文网首页
小程序圆环图(svg实现)

小程序圆环图(svg实现)

作者: 清霆 | 来源:发表于2024-05-06 09:48 被阅读0次
function getRingStyle(props: {
  percent: number
  duration: number
  radius: number
  ringWidth: number
  activeColor?: string
  inactiveColor?: string
}) {
  const {
    percent,
    duration,
    radius,
    ringWidth,
    activeColor = '',
    inactiveColor = '',
  } = props
  const getRingLength = (deg = 0, r = 80) => (deg / 100) * (2 * Math.PI * r)
  const maxLength = getRingLength(100)

  const ringWidth2 = (ringWidth / radius) * 80
  const rate = ringWidth2 / 160
  const strokeWidth = (160 * rate) / (1 - rate)
  const wh = 160 + strokeWidth
  const cx = 120 - strokeWidth / 2
  const cy = 80 + strokeWidth / 2
  const svg = `<svg width="${160}" height="${160}" viewBox="0 0 ${wh} ${wh}" fill="none" xmlns="http://www.w3.org/2000/svg">
  <circle
    cx="${cx}"
    cy="${cy}"
    r="80"
    fill-opacity="0"
    stroke-width="${strokeWidth}"
    stroke="${inactiveColor}"
    stroke-opacity="1"
    stroke-dasharray="${maxLength} ${maxLength}"
    stroke-linecap="round"
    transform="rotate(-90 100 100)"
  >
  </circle>
  <circle
    cx="${cx}"
    cy="${cy}"
    r="80"
    fill-opacity="0"
    stroke-width="${strokeWidth}"
    stroke="${activeColor}"
    stroke-opacity="1"
    stroke-dasharray="0 ${maxLength}"
    stroke-linecap="round"
    transform="rotate(-90 100 100)"
    style="transition: stroke-dasharray ${duration / 1000}s linear;"
  >
    <set attributeName="stroke-dasharray" attributeType="XML" to="${getRingLength(
      percent
    )} ${maxLength}" begin="0s" />
  </circle>
</svg>`

  return {
    backgroundImage: `url(data:image/svg+xml;base64,${base64.encode(svg)})`,
    backgroundSize: '100% 100%',
  }
}

相关文章

网友评论

      本文标题:小程序圆环图(svg实现)

      本文链接:https://www.haomeiwen.com/subject/xqelfjtx.html