【发布时间】:2021-02-02 02:54:43
【问题描述】:
我有一个正在运行的 Angular 9 应用程序,其中 SVG 有一个螺旋图,其中包含度数的最小值和最大值。 我正在使用 d3.js 在螺旋图上绘制给定的度数。 我写了以下代码:
// min -> min degree, -140 in this example
// max -> max degree, 440 in this example
// currentDegree -> degree value to be ploted, 0 in this example
// svg -> svg containing spiral chart
// circle -> circle to be moved to depict current Degree position in the svg
void setDegree(min,max,currentDegree, svg, circle) {
const pathNode = svg.select('path').node();
const totalPathLength = pathNode.getTotalLength();
const yDomain = d3.scale.linear().domain([min, max]).range(
[0, totalPathLength]);
const currentPathLength = yDomain(currentDegree); // current path length
const pathPoint = pathNode.getPointAtLength(totalPathLength - currentPathLength);
circle.transition()
.duration(300)
.attrTween('cx', () => (t) => pathPoint.x)
.attrTween('cy', () => (t) => pathPoint.y);
}
上面的代码产生这个输出:
在上图中,0 度略微向右移动,但它应该位于中心,如下图所示:
function setDegree(min, max, currentDegree, svg, circle) {
const pathNode = svg.select("path").node();
const totalPathLength = pathNode.getTotalLength();
const yDomain = d3
.scaleLinear()
.domain([min, max])
.range([0, totalPathLength]);
const currentPathLength = yDomain(currentDegree); // current path length
const pathPoint = pathNode.getPointAtLength(
totalPathLength - currentPathLength
);
circle
.transition()
.duration(300)
.attrTween("cx", () => t => pathPoint.x)
.attrTween("cy", () => t => pathPoint.y);
}
const svg = d3.select("svg");
const circle = d3.select("#cur_pos");
setDegree(-140, 410, 0, svg, circle);
p {
font-family: Lato;
}
.cls-3 {
fill: none;
stroke-width: 10px;
stroke: #000;
}
.cls-3,
.cls-4,
.cls-5 {
stroke-miterlimit: 10;
}
.cls-4,
.cls-5 {
stroke-width: 0.25px;
}
.cls-5 {
font-size: 60px;
font-family: ArialMT, Arial;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1031.1 1010.3" preserveAspectRatio="xMinYMin meet">
<title>Spiral Chart</title>
<g>
<g id="Spiral_Chart">
<g id="Spiral_Path">
<path
class="cls-3 svg-range-line"
d="M881.5,154.9C679.6-47,352.3-47,150.4,154.9c-195.9,195.9-195.9,513.4,0,709.3,189.7,190,497.5,190.1,687.5.4l.4-.4c184.3-184.3,184.3-483,0-667.3h0C659.6,18.1,369.8,18.1,191.1,196.8H191C17.6,370.3,17.6,651.4,191,824.8"
/>
</g>
<circle
id="cur_pos"
class="cls-4 svg-range-indicator"
cx="514"
cy="64.3"
r="18.5"
/>
</g>
<text
id="Min"
class="cls-5 svg-text"
style="text-anchor:start;"
x="195"
y="880"
>
-140
</text>
<text
id="Max"
class="cls-5 svg-text"
style="text-anchor:start;"
x="885"
y="210"
>
410
</text>
</g>
</svg>
【问题讨论】:
-
你已经让你的范围等于路径的长度,这意味着如果路径不小心出错了,那么零点也会在错误的位置。您能否将您的代码更改为minimal reproducible example,特别是可运行的sn-p?可以在这里,或者如果你愿意,可以通过 jsfiddle/codepen/observablehq。它将帮助您获得更好的答案
-
在此处添加运行示例:stackblitz.com/edit/angular-ivy-scb3s9
标签: javascript angular d3.js