首页 > 解决方案 > 如何根据svg长度设置时间?

问题描述

我正在学习 javascript 并做出反应,在这里我陷入了必须根据 SVG 图像的长度(类似于进度条)设置时间的挑战中。

举一个简单和基本的例子,我在 1440 分钟内计算 24 小时的总时间,我给出了过去的时间let passedMins = 1220

现在我需要根据经过的时间在 svg 圆圈中填充绿线。就像每一分钟的绿线应该加起来更多

import React, {
  useState,
  useEffect
} from 'react';

function Clock(props) {

  useEffect(() => {
    const circle = document.querySelector('circle');
    const circleLength = Math.floor(circle.getTotalLength());
    const perMinArea = circleLength / 1440;
    let passedMins = 1220;
    const fillArea = passedMins * perMinArea;
    circle.style.strokeDasharray = circleLength - fillArea;
    // circle.style.strokeDashoffset = circleLength -fillArea;

  }, [props.time])

  return (
    <div className = "clock-space" >
      <div className = "clock" >{props.time}</div>
      <svg width = "130" height = "130" className = "circle" viewBox = "0 0 130 130" fill = "none" xmlns = "http://www.w3.org/2000/svg">
        <circle cx="65" cy="65" r="61.5" stroke="lightgreen" strokeWidth="7"/>
      </svg>
    </div >
  );
}

export default Clock;

它看起来像这样:

圆圈的图像

它显示了 3 行我只想要一个。有什么建议可以解决吗?

标签: javascripthtmlreactjs

解决方案


您还需要将圆的长度传递给circle.style.strokeDasharray. 为此,您需要根据圆圈的总长度来获取“剩余分钟数”的长度。请看下面的例子。

const circle = document.querySelector('circle');
const timeLeftLabel = document.getElementById('time-left');
const circleLength = Math.floor(circle.getTotalLength());
const maxMinutes = 1440;
let passedMins = 1220;
let minsLeft = maxMinutes - passedMins;

// get percentage of minutes left
let minsLeftPercentage = minsLeft / maxMinutes;

// x % of length where x  = minsLeftPercentage
let leftLength = minsLeftPercentage * circleLength;

//combine leftLength and circleLength into comma-separated string
circle.style.strokeDasharray = leftLength + ',' + circleLength;

//just simple implementation for the {props.time} 
timeLeftLabel.innerText = minsLeft + ' minutes left';
<div className="clock-space">
  <div className="clock" id="time-left"></div>
  <svg width="130" height="130" className="circle" viewBox="0 0 130 130" fill="none" xmlns="http://www.w3.org/2000/svg">
        <circle cx="65" cy="65" r="61.5" stroke="lightgreen" strokeWidth="7"/>
      </svg>
</div>


推荐阅读