Creating a CSS linear gradient based on two points relative to a rectangle

前端 未结 2 1521
野趣味
野趣味 2021-01-06 18:38

I am trying to recreate the gradient tool in Sketch. The tool in Sketch is using two points with different colors to define a gradient:

I want the output to

2条回答
  •  [愿得一人]
    2021-01-06 19:20

    This was the way I solved it!

    If you look at the GIF I have attached which illustrates the points I am using in my calculations. The red line is the gradient line in the center of the rectangle and the black points are the start and end points of the gradient line. The two other points (black and white) is the user controlled points that the user can drag around any way he likes. The two red dots are the closest position on the line relative to each user controlled point (perpendicular line points, p1 and p2).

    I get the distance between the perpendicular line points and the gradient line start and end points. And then to calculate the percent value needed for the CSS linear-gradient value, I add the two distances, dived them by the gradient line length and multiply the value by 100.

    ax = ((p1.x - gradientLine.point1.x) * (gradientLine.length / 2)) / (gradientLine.point2.x - gradientLine.point1.x);
    ay = ((p1.y - gradientLine.point1.y) * (gradientLine.length / 2)) / (gradientLine.point2.y - gradientLine.point1.y);
    
    percentValue = (((ax + ay) / line.length) * 100);
    

    To get the value for the second parameter in the linear-gradient value I just do kind of the same thing, except I subtract 100 with the calculate value.

    ax = ((p2.x - gradientLine.point2.x) * (gradientLine.length / 2)) / (gradientLine.point1.x - gradientLine.point2.x);
    ay = ((p2.y - gradientLine.point2.y) * (gradientLine.length / 2)) / (gradientLine.point1.y - gradientLine.point2.y);
    percentValue = 100 - ((((ax + ay) / gradientLine.length) * 100));
    

    This way I get two percent values and can easily construct my CSS linear-gradient value consisting off the angle of the two user controlled points plus the two percent values I calculate:

    background: linear-gradient([angle]deg, black [percentValue1]%, white [percentValue2]%)
    

提交回复
热议问题