当路径长度发生变化时,保持笔划dasharray的一致性



我有一个由用户使用D3.js.绘制的路径

我希望在用户绘制的路径上定义一个dasharray,但是,当它改变形状和长度时,dasharray的行为不一致,间隙也在移动并变得更小。

这是一个代码笔:

https://codepen.io/Richacinas/pen/YjXpBE

随意分叉。绘制用户路径的函数是这样的:

DrawItGraph.prototype.draw = function() {
...
var pos = this.d3.mouse(event.target)
if (pos[1] > this.chartHeight) return
var date = this.clamp(this.middleValue + 2629743, this.maxValue, this.convection.x.invert(pos[0]))
var value = this.clamp(0, this.convection.y.domain()[1], this.convection.y.invert(pos[1]))
this.userData.forEach(function (d) {
if (Math.round(Math.abs(d.date - date) / 60000000) < 50) {
d.value = value
d.defined = true
}
})
this.yourDataSel.at({d: this.line.defined(this.format('defined'))(this.userData)})
if (this.d3.mean(this.userData, this.format('defined')) === 1) {
this.graphCompleted = true
}
}

我怀疑我必须根据路径长度动态更改笔划dashoffset和/或笔划dasharray,然而,我不知道什么是正确的公式。。。

非常感谢

问题不在于短划线数组或短划线偏移量。让我们看一个生成路径的例子:

.your-line {
stroke: #ffb531;
stroke-width: 10;
stroke-dasharray: 15;
}
<svg width="600" viewBox="1000 0 800 440">
<path class="your-line" d="M1031.9776744186047,214L1099.9652386780906,189L1170.1216156670746,188L1238.0148837209304,188L1308.1712607099143,153.00000000000006L1378.3276376988983,174.00000000000003L1446.1266095471235,163.00000000000006L1516.2829865361077,218.99999999999997L1584.1762545899633,201L1654.3326315789475,201L1724.4890085679315,114.99999999999994L1787.85605875153,195L1858.012435740514,195L1858.012435740514,195L1787.85605875153,195L1724.4890085679315,114.99999999999994L1654.3326315789475,201L1584.1762545899633,201L1516.2829865361077,218.99999999999997L1446.1266095471235,163.00000000000006L1378.3276376988983,174.00000000000003L1308.1712607099143,153.00000000000006L1238.0148837209304,188L1170.1216156670746,188L1099.9652386780906,189L1031.9776744186047,214Z"></path>
</svg>

如果我们去掉前几个坐标和最后几个坐标,问题应该会变得很明显:

M 1031, 214
L 1099, 189
L 1170, 188
...
L 1170, 188
L 1099, 189
L 1031, 214
Z

你的问题是,你画的不是一条线,而是一条向左走,然后再回来的路径,在相同的坐标上,一直走到起点。

随着路径长度的变化,破折号图案会干扰自身,使破折号看起来会增长和收缩。

您需要更新划线代码才能仅在一个方向上绘制路径。不是闭合形状。

最新更新