计算第二行的Y1,它是第一行大小的一半

时间:2019-03-16 13:40:34

标签: javascript math

我有一行具有以下值(x1,y1,x2,y2):

20, 100, 120, 120

如何获取第二行Y1,使其与第一行Y1的高度相同(第二行的大小是一半,或与第一行不同)?

70, 100, 120, 120

第二行看起来与上面的值相同,

enter image description here 输出也应如下图所示:

enter image description here

1 个答案:

答案 0 :(得分:1)

公式方法:

console.log(getCoordinates(20,10,120,50,1/4));
console.log(getCoordinates(60,10,160,50,1/2));
console.log(getCoordinates(100,10,200,50,3/4));

//factor = 1/2 if 50%
//factor = 3/4 if 75% and so on
function getCoordinates(x1, y1, x2, y2, factor){
let x3 = 0,
    y3 = 0;

x3 = (x2-x1)*factor+x1;
y3 = (y2-y1)*factor+y1;

return {x3:x3, y3:y3}
}
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
<line x1="20" y1="10" x2="120" y2="50" stroke="red" />
<line x1="45" y1="20" x2="120" y2="50" stroke="green" />

<line x1="60" y1="10" x2="160" y2="50" stroke="blue" />
<line x1="110" y1="30" x2="160" y2="50" stroke="orange" />

<line x1="100" y1="10" x2="200" y2="50" stroke="black" />
<line x1="175" y1="40" x2="200" y2="50" stroke="yellow" />


<line x1="20" y1="100" x2="120" y2="120" stroke="red" />
<line x1="45" y1="105" x2="120" y2="120" stroke="green" />

<line x1="60" y1="100" x2="160" y2="120" stroke="blue" />
<line x1="110" y1="110" x2="160" y2="120" stroke="orange" />

<line x1="100" y1="100" x2="200" y2="120" stroke="black" />
<line x1="175" y1="115" x2="200" y2="120" stroke="yellow" />

</svg>

第二种方法:

您可以考虑使用渐变来获得看起来像您想要的输出。

<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">

<line x1="15" y1="5" x2="120" y2="120" stroke="url(#myGradient25)" />

<line x1="25" y1="5" x2="130" y2="120" stroke="url(#myGradient75)" />

<line x1="35" y1="5" x2="140" y2="120" stroke="url(#myGradient50)" />

 
  
  <!-- Stroke a circle with a gradient -->
  <defs>
    <linearGradient id="myGradient25">
      <stop offset="25%"   stop-color="red" />
      <stop offset="25%" stop-color="green" />
    </linearGradient>
  </defs>

  <!-- Stroke a circle with a gradient -->
  <defs>
    <linearGradient id="myGradient75">
      <stop offset="75%"   stop-color="red" />
      <stop offset="75%" stop-color="green" />
    </linearGradient>
  </defs>
  
   <!-- Stroke a circle with a gradient -->
  <defs>
    <linearGradient id="myGradient50">
      <stop offset="50%"   stop-color="red" />
      <stop offset="50%" stop-color="green" />
    </linearGradient>
  </defs>
</svg>