同一页面上多个<canvas>元素的Init脚本

时间:2018-02-20 10:39:52

标签: jquery foreach gradient repeat

我使用名为Granim的jQuery渐变动画脚本来生成平滑的背景渐变,我发现它看起来比CSS渐变更好。

目前,当我初始化脚本时,它只适用于页面上的第一个元素,但我希望它在我页面上的许多元素上重复工作。

是否可以在页面中的多个重复元素上使用Granim?

谢谢。

HTML

<canvas class="gradient-bg">It works on this one!</canvas>
<canvas class="gradient-bg">Doesn't work on this one</canvas>
<canvas class="gradient-bg">Doesn't work on this one</canvas>
<canvas class="gradient-bg">Doesn't work on this one</canvas>
<canvas class="gradient-bg">Doesn't work on this one</canvas>

JQUERY

// init
var newInstance = new Granim({
    element: '.gradient-bg',
    defaultStateName: 'state-1,
    direction: 'left-right',
    opacity: [1,1,1,1],
    isPausedWhenNotInView: true,
        states : {
            "state-1": {
                gradients: [
                    ['#AA076B', '#61045F'],
                    ['#02AAB0', '#00CDAC']
            ],
            transitionSpeed: 2500
           }
    }
});

1 个答案:

答案 0 :(得分:1)

Granim documentation中,它指出element属性可以是字符串或HTMLCanvasElement,因此您只需循环遍历.gradient-bg元素并将其作为对实例化调用的引用:

$('.gradient-bg'.each(function() {
  var newInstance = new Granim({
    element: this, // note reference here
    defaultStateName: 'state-1',
    direction: 'left-right',
    opacity: [1, 1, 1, 1],
    isPausedWhenNotInView: true,
    states: {
      "state-1": {
        gradients: [
          ['#AA076B', '#61045F'],
          ['#02AAB0', '#00CDAC']
        ],
        transitionSpeed: 2500
      }
    }
  });
});