【问题标题】:How can I change the attributes of a SVG line?如何更改 SVG 线的属性?
【发布时间】:2017-01-25 15:40:25
【问题描述】:

有两条线“LongLine”和“ShortLine”。

<svg width="120" height="120" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
<line id="LongLine" x1="20" y1="350" x2="350" y2="50" stroke-width="2" stroke="black"/>
<line id="ShortLine" x1="20" y1="350" x2="0" y2="0" stroke="#ff00ff" stroke-width="10" />
</svg>
我想更改“ShortLine”的属性。 “短线”必须具有相同的角度,但比“长线”短。 “ShortLine”的属性可以是例如如下(x1="20" y1="350" x2="185" y2="200")。

<svg width="120" height="120" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
<line id="LongLine" x1="20" y1="350" x2="350" y2="50" stroke-width="2" stroke="black"/>
<line id="ShortLine" x1="20" y1="350" x2="185" y2="200" stroke="#ff00ff" stroke-width="10" />
</svg>

换句话说,“LongLine”的 x1, y1, x2, y2 和“ShortLine”的 x1, y1 是已知的。
需要的是“ShortLine”的 x2、y2,但要使两条线的角度保持不变。

这是我的错误做法:https://jsfiddle.net/rmLdm15z/8/

提前致谢。

【问题讨论】:

  • 你想让短线的斜率和长线的斜率一样吗?
  • 是的,两条线的角度和坡度应该保持不变。

标签: javascript html svg


【解决方案1】:

试试这个:

var shortLine = document.getElementById('ShortLine')
shortLine.y1.baseVal.value = 500

console.log(shortLine)
// Gives us:
// <line id="ShortLine" x1="20" y1="500" x2="185" y2="200" stroke="#ff00ff" stroke-width="10"></line>

作为一般准则,您始终可以通过控制台查看对象提供给您的所有属性。比如console.log(shortLine.y1)就是你发现可以设置baseVal.value的方式。

【讨论】:

  • 不知道你的意思?它对我不起作用。见这里:link
  • 您的问题是如何更改 svg 属性 - 因此我的回答展示了如何做到这一点。
  • 非常感谢您的回答。我的问题的标题是这样,但我的问题包含解释。无论如何,我很感谢你的回答;)
【解决方案2】:

一种方法是计算“LongLine”的点(x1, y1)(x2, y2)给出的单位向量u,然后将其添加到(x1, y1)乘以“ShortLine”所需的大小,调用它short_d

const dx = x2 - x1
const dy = y2 - y1
const d = Math.sqrt(dx * dx + dy * dy)
const ux = dx / d
const uy = dy / d

const shortLine = document.getElementById('ShortLine')
shortLine.setAttribute('x1', `${x1}`)
shortLine.setAttribute('y1', `${y1}`)
shortLine.setAttribute('x2', `${x1 + short_d * ux}`)
shortLine.setAttribute('y2', `${y1 + short_d * uy}`)

看看Vector algebra

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2014-09-21
    相关资源
    最近更新 更多