javascript - 如何根据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 行我只想要一个。有什么建议可以解决吗?
解决方案
您还需要将圆的长度传递给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>
推荐阅读
- python - 在烧瓶中可以在应用程序之外呈现模板吗?
- java - 使用 LinkedIn 进行身份验证时缺少“client_id”
- java - 字符串实习生()方法
- javascript - 单击按钮后,name.forEach 不是函数
- javascript - Node.js util.promisify - 将标准输出输出为 obj 或数组而不是新行
- c# - WPF MetroWindow 列表框删除焦点颜色
- shortest-path - 如何在 O(mn) 中找到最短路径
- spring - 如何检索多个选择选项?
- javascript - Angular 6材料表添加最后输入值的行(表单域)
- java - 流的收集方法的有效供应商