简体   繁体   English

如何更改 SVG 线的属性?

[英]How can I change the attributes of a SVG line?

There are two lines "LongLine" and "ShortLine".有两条线“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>
I want to change the attributes of "ShortLine". 我想更改“ShortLine”的属性。 The "ShortLine" must have the same angle, but it is short than "LongLine". “ShortLine”必须有相同的角度,但比“LongLine”短。 The attributes of "ShortLine" could be eg as follows (x1="20" y1="350" x2="185" y2="200"). “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>

In other words x1, y1, x2, y2 of "LongLine", and x1, y1 of "ShortLine" are known.换句话说,“LongLine”的x1、y1、x2、y2和“ShortLine”的x1、y1是已知的。
Wanted are the x2, y2 of "ShortLine", but so that the angle of both lines remains the same.想要的是“ShortLine”的 x2, y2,但这样两条线的角度保持不变。

Here is my wrong approach: https://jsfiddle.net/rmLdm15z/8/这是我的错误方法: https : //jsfiddle.net/rmLdm15z/8/

Thanks in advance.提前致谢。

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 .例如, console.log(shortLine.y1)是您发现可以设置baseVal.value

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

Take a look on Vector algebra .看看向量代数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM