更改路径长度时,使笔划-dasharray保持一致

时间:2018-07-12 10:56:43

标签: javascript d3.js svg

我使用D3.js绘制了一条由用户绘制的路径。

我想在用户绘制的路径上定义一个破折号数组,但是,随着其形状和长度的改变,破折号的行为会变得不一致,并且间隙会不断变小。

这是一个codepen:

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
    }
}

我怀疑我必须根据路径长度动态更改stroke-dashoffset和/或stroke-dasharray,但是,我不知道合适的公式是什么...

非常感谢

1 个答案:

答案 0 :(得分:5)

您的问题不是破折号数组或破折号偏移量。让我们看一个示例生成的路径:

.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

您的问题是您没有画一条线,而是在一条路径上向左移动,然后再以相同的坐标返回到起点。

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

您需要更新线条图代码以仅在一个方向上绘制路径。不是封闭的形状。