如何计算CSS渐变路径?

时间:2017-01-05 20:08:26

标签: css algorithm colors linear-gradients

使用线性渐变时,例如



div {
  width: 300px;
  height: 50px;
  background: linear-gradient(to right, blue, red);
}

<div></div>
&#13;
&#13;
&#13;

颜色可以通过不同的路径改变。

在上面的示例中,可以通过线性修改RB频道来完成,而无需触及G频道 - 但变体也可以是线性(提供线性感,因为它更具生理性),或通过修补G频道(再次因为它似乎是一个更现实的红色到蓝色过渡&# 39;对我们来说。)

linear-gradient用于在两种颜色之间切换的公式是什么?

1 个答案:

答案 0 :(得分:1)

HTML / CSS中的渐变是线性插值,纯粹是数学的。根据W3C画布规范:

  

一旦创建了渐变(见下文),就会沿着它放置停止点以定义颜色沿渐变的分布方式。每个停靠点的渐变颜色是为该停止指定的颜色。在每个这样的停止之间,颜色和alpha分量必须在RGBA空间上线性插值,而不预先乘以α值以找到在该偏移处使用的颜色。在第一站之前,颜色必须是第一站的颜色。在最后一站之后,颜色必须是最后一站的颜色。当没有停止时,渐变是透明的黑色。

SVG以同样的方式工作。

CSS渐变是相同的,除了一个区别(强调我的):

  

在两个色标之间,线的颜色在两个色标的颜色之间进行插值,插值在预乘的RGBA 空间中进行。

所以这三个都使用线性插值,而canvas / SVG使用非预乘alpha,而CSS使用预乘alpha(看起来确实更好)。至于为何会产生影响,请参阅此示例:

&#13;
&#13;
html, body, svg, div {
  display: block;
  width: 100%;
  height: 100%;
  margin: 0; 
  padding: 0;
  background: white;
}
svg {height: 60%;}
div.gradient {
  height: 20%;
  margin-top: 0.2%;
  background: linear-gradient(to right,
  rgba(0%, 100%, 0%, 1),
  rgba(0,0,0,0));
}
&#13;
<svg>
  <linearGradient id="a">
    <stop offset="0" stop-color="lime"
      stop-opacity="1" />
    <stop offset="1" stop-color="lime"
      stop-opacity="0" />
  </linearGradient>
  <linearGradient id="b">
    <stop offset="0" stop-color="lime"
      stop-opacity="1" />
    <stop offset="1" stop-color="black"
      stop-opacity="0" />
  </linearGradient>
  <linearGradient id="c">
    <stop offset="0" stop-color="rgba(0%, 100%, 0%, 1)" />
    <stop offset="1" stop-color="rgba(0,0,0,0)" />
  </linearGradient>
  <rect width="100%" height="33%"
    fill="url(#a)" />
  <rect width="100%" height="33%" y="33.5%"
    fill="url(#b)" />
  <rect width="100%" height="33%" y="67%"
    fill="url(#c)" />
</svg>
<div class="gradient"></div>
<ul>
  <li>Top: SVG gradient with constant stop-color and transitioned stop-opacity;</li>
  <li>2nd: SVG gradient with stop-color transitioning to black and stop-opacity transitioning to zero;</li>
  <li>3rd: SVG gradient with rgba colors;</li>
  <li>Bottom: CSS gradient with the same rgba colors.</li>
</ul>
<p>All transition from opaque lime to fully transparent; in all but the first SVG gradient, the final stop is transparent black.  The CSS gradient scales the intensity of the color by the alpha value before transitioning, so you don't get the fade to gray effect.</p>
&#13;
&#13;
&#13;

免责声明:那不是我的片段!我从CodePen example获取了它,但是我不会在没有自己添加代码的情况下链接到它。