KaSkuLL
KaSkuLL

Reputation: 551

Random gradient background color

i'm trying to get a random gradient background (between 4 colours) on each section. This is my code:

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){   
        let firstGradient = randomNumber(10,90);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)]+" "+(100-firstGradient)+"%)"
        );
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <section></section>
  <section></section>
  <section></section>
</div>

It is so random. Sometimes i get results like this: enter image description here

When result should be something like this:

enter image description here

Upvotes: 5

Views: 6997

Answers (2)

Jamiec
Jamiec

Reputation: 136154

If you dont try to calculate the remaining % then it seems to work as you expect

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){   
        let firstGradient = randomNumber(10,90);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)] + ")"
        );
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <section></section>
  <section></section>
  <section></section>
</div>

Upvotes: 2

Elijah Ellanski
Elijah Ellanski

Reputation: 922

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){   
        let firstGradient = randomNumber(10,40);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)]+" "+(100-firstGradient)+"%)"
        );
        "background", "linear-gradient(141deg, #0fb8ad 0%, #1fc8db 51%, #2cb5e8 75%)" 
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <section></section>
  <section></section>
  <section></section>
</div>

If your first gradient position is bigger then 50%, the second is smaller then first. for example gradient from red 60% to green 40% will be a straight line. fixed your randomNumber to always be <50

And obviously you get no blur when gradient from and to are the same color

Upvotes: 0

Related Questions