Javascript 如何更改SVG行的属性?

Javascript 如何更改SVG行的属性?,javascript,html,svg,Javascript,Html,Svg,有两条线“长线”和“短线”。 试试这个: 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"></

有两条线“长线”和“短线”。

试试这个:

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>
var shortLine=document.getElementById('shortLine'))
shortLine.y1.baseVal.value=500
控制台日志(短线)
//给了我们:
// 

一般来说,您可以通过控制台查看对象提供给您的所有属性。例如,
console.log(shortLine.y1)
是如何设置
baseVal.value
一种方法是计算单位向量
u
,该单位向量由“长线”的点
(x1,y1)
(x2,y2)
给出,然后将其添加到
(x1,y1)
乘以所需的“短线”大小,称之为
short\u 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', `${y2 + short_d * uy}`)

看看。

你想让短线的坡度和长线的一样吗?是的,两条线的角度和坡度应该保持不变。我不知道你的意思?这对我不起作用。请看这里:您的问题是如何更改svg属性-因此我的答案演示了如何准确地执行此操作。非常感谢您的回答。我的问题的标题是,但我的问题包含解释。无论如何,我很感谢你的回答;)