以编程方式设置渐变

时间:2016-02-14 11:59:02

标签: javascript css

我正在尝试使用计算样本数组为元素设置线性渐变背景。

目前,我有这个样式表(jsfiddle here):

.element
    background linear-gradient(180deg, #92c3ff, #ff8e87, #fcfb83)
    background-size 600% 600%
    animation BackgroundAnimation 20s ease infinite

@keyframes BackgroundAnimation
   0% {
   background-position 50% 0
   }
   50% {
   background-position 50% 100%
   }
   100% {
   background-position 50% 0
   } 

如上所示,我不想对样式表中的颜色进行硬编码,而是使用计算样本数组。样本在Vibrant.js的帮助下计算,如下所示:

var img = document.createElement('img');
img.setAttribute('src', './path/to/image.png');

img.addEventListener('load', function() {
var vibrant = new Vibrant(img);
var swatches = vibrant.swatches();
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch])

我可以轻松设置所选元素的背景颜色(纯色,单色),如下所示:

var element = document.querySelector(".element");

element.style.backgroundColor = vibrant.DarkVibrantSwatch.getHex();

// element.style.backgroundColor = vibrant.VibrantSwatch.getHex();
// element.style.backgroundColor = vibrant.MutedSwatch.getHex();
// element.style.backgroundColor = vibrant.DarkMutedSwatch.getHex();
// element.style.backgroundColor = vibrant.LightMutedSwatch.getHex();

但是,我怎么可能用所有现有样本而不是单一颜色背景设置渐变?此外,我将如何制作动画?

1 个答案:

答案 0 :(得分:2)

这个解决方案对我有用:

var img = document.getElementById("image");

img.addEventListener('load', function() {
  var vibrant = new Vibrant(img);
  var swatches = vibrant.swatches();
  for (var swatch in swatches)
    if (swatches.hasOwnProperty(swatch) && swatches[swatch]) 
     console.log(swatch, swatches[swatch].getHex());

      var gradColors = [
      vibrant.DarkVibrantSwatch.getHex(),
      vibrant.VibrantSwatch.getHex(),
      vibrant.MutedSwatch.getHex(),
      vibrant.DarkMutedSwatch.getHex(),
      vibrant.LightMutedSwatch.getHex()
      ];

      console.log(gradColors);

      var element = document.querySelector('.element');

      element.style.background = 'linear-gradient(180deg,' + gradColors.join() + ')';
      element.style.backgroundSize = '600% 600%';
      element.style.animation = 'BackgroundAnimation 5s ease infinite';

});

首先,它计算给定图像的主色(它使用Vibrant.js来完成此操作),然后为.element设置背景渐变并为其设置动画。它通过访问它的一些样式属性来实现,即backgroundanimation

jsfiddle here