【问题标题】:Keep stroke-dasharray consistent when path length is changing路径长度变化时保持 stroke-dasharray 一致
【发布时间】:2018-07-12 22:03:02
【问题描述】:

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

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

这是一个代码笔:

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

随意fork..绘制用户路径的函数就是这个:

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,但是,我不知道正确的公式是什么...

非常感谢

【问题讨论】:

    标签: javascript d3.js svg


    【解决方案1】:

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

    .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
    

    你的问题是你没有画一条线,你画的是一条向左行进的路径,然后在相同的坐标上再次返回到起点。

    随着路径长度的变化,破折号图案会相互干扰,使破折号看起来会变长或缩小。

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

    【讨论】:

    • 雄伟。非常感谢保罗,它现在像水一样清澈。我将尝试在此处发布带有解决方案的 codepen 的分支
    • 我正在尝试解决这个问题,但这并不容易......出于某种原因,正如你所说,我正在创建一条双倍长度的线,然后返回,但是我不知道为什么。
    • 我希望它是您使用 d3 生成的图形类型。我不是 d3 用户,所以我无法就下一步做什么提供任何建议。对不起。
    猜你喜欢
    • 2013-12-23
    • 2015-03-17
    • 2021-01-01
    • 1970-01-01
    • 2019-03-13
    • 2021-08-08
    • 1970-01-01
    • 2018-05-12
    • 2019-08-18
    相关资源
    最近更新 更多