1

Есть такой код который должен плавно менять цвет

setInterval(() => {
   document.getElementById('backgroundLinear').style.background = 'linear-gradient(-90deg, '+ randomColor +' 0, rgba(76, 229, 180, 0))';
   document.getElementById('backgroundLinear').style.transition = '5s';
}, SEC_INTERVAL * 1000);

Проблема в том что он меняет цвет но не плавно. Как выйти из данной ситуации ?

1
  • 1
    градиенты не анимируются - придётся искать другое решение 4 мар 2019 в 15:16

1 ответ 1

3

Ну если пораскинуть мозгами, то мы генерируем,а списком показываем какие именно нужны градиенты это массив цветов colors: смотрим пример

Как анимировать градиент подсмотрел здесь

И да забыл написать что у вас там ошибочка...sec interval к примеру и вы должны были сделать функцию и в сет интервале обновлять значения вашей функции ..

в общем Дэмо на лицо

    var colors = new Array(
        [62,35,255],
        [60,255,60],
        [255,35,98],
        [45,175,230],
        [255,0,255],
        [255,128,0]);

    var step = 0;

    var colorIndices = [0,1,2,3];

    var gradientSpeed = 0.002;

    function updateGradient()
    {

        if ( $===undefined ) return;

        var c0_0 = colors[colorIndices[0]];
        var c0_1 = colors[colorIndices[1]];
        var c1_0 = colors[colorIndices[2]];
        var c1_1 = colors[colorIndices[3]];

        var istep = 1 - step;
        var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
        var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
        var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
        var color1 = "rgb("+r1+","+g1+","+b1+")";

        var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
        var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
        var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
        var color2 = "rgb("+r2+","+g2+","+b2+")";

        $('#gradient').css({
            background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({
            background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

        step += gradientSpeed;
        if ( step >= 1 )
        {
            step %= 1;
            colorIndices[0] = colorIndices[1];
            colorIndices[2] = colorIndices[3];

 
            colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
            colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;

        }
    }

    setInterval(updateGradient,10);
#gradient{
  width:500px;
  height:400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="gradient"></div>

2

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.