基于相对于矩形的两个点创建CSS线性渐变 [英] Creating a CSS linear gradient based on two points relative to a rectangle

查看:112
本文介绍了基于相对于矩形的两个点创建CSS线性渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Sketch中重新创建渐变工具。 Sketch中的工具使用两个不同颜色的点来定义渐变:





我希望输出采用CSS线性渐变值的形式。构建CSS线性渐变的方式是使用颜色和百分比定义的角度和x个颜色停止点:


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 be in the form of a CSS linear gradient value. The way a CSS linear gradient is constructed is an angle and x number of color stops with a color and a percentage defined: https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

So I want to convert two points relative to the rectangle in which the gradient should be rendered to the CSS format (two parameters with the correct percentage).

Any ideas on how to approach this problem?

解决方案

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]%)

这篇关于基于相对于矩形的两个点创建CSS线性渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆