user3815508
user3815508

Reputation: 399

How can I change the attributes of a SVG line?

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>

In other words x1, y1, x2, y2 of "LongLine", and x1, y1 of "ShortLine" are known.
Wanted are the x2, y2 of "ShortLine", but so that the angle of both lines remains the same.

Here is my wrong approach:https://jsfiddle.net/rmLdm15z/8/

Thanks in advance.

Upvotes: 4

Views: 4924

Answers (2)

Samuel
Samuel

Reputation: 1421

One way is to calculate the unit vector u given by the points (x1, y1) and (x2, y2) of the "LongLine", then add it to (x1, y1) multiplied by the desired size of the "ShortLine", call it 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}`)

Take a look on Vector algebra.

Upvotes: 1

Jared Reich
Jared Reich

Reputation: 257

Try this:

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>

As a general guideline, you can always view all the properties an object gives you through the console. For example, console.log(shortLine.y1) is how you find that you can set baseVal.value.

Upvotes: 6

Related Questions