如何更改SVG线条的属性?

4

There are two lines "LongLine" and "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>

I want to change the attributes of "ShortLine". The "ShortLine" must have the same angle, but it is short than "LongLine". The attributes of "ShortLine" could be e.g. as follows (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/
提前感谢您的帮助。

你想让短线的斜率与长线相同吗? - Mitesh Pant
是的,两条线的角度和斜率应该保持不变。 - user3815508
2个回答

6

试试这个:

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


我不知道你的意思?对我来说它不起作用。请看这里:链接 - user3815508
你的问题是如何更改SVG属性 - 因此我的答案演示了如何做到这一点。 - Jared Reich
非常感谢您的回答。我的问题标题是这样的,但我的问题中包含了解释。无论如何,我很感激您的答复 ;) - user3815508

1
一种方法是计算由“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}`)

看看向量代数


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接