有两行" 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>
&#13;
<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>
&#13;
换句话说,&#34; LongLine&#34;的x1,y1,x2,y2,以及&#34; ShortLine&#34;的x1,y1;众所周知。
想要的是&#34; ShortLine&#34;的x2,y2,但两条线的角度保持不变。
这是我错误的做法:https://jsfiddle.net/rmLdm15z/8/
提前致谢。
答案 0 :(得分:2)
试试这个:
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
。
答案 1 :(得分:1)
一种方法是计算“ LongLine”的点u
和(x1, y1)
给定的单位向量(x2, y2)
,然后将其加到(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', `${y2 + short_d * uy}`)