Advertisement
retesere20

gradient background javascript

Mar 1st, 2020
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1.  
  2. // ======================================= Random Gradient Backgroud ======================================
  3. function animiatedGradientBackground(selector){
  4. var colors = array_shuffle(new Array(
  5. [62,35,255],
  6. [60,255,60],
  7. [255,35,98],
  8. [45,175,230],
  9. [255,0,255],
  10. [255,128,0]));
  11. var step = 0;
  12. //color table indices for:
  13. // current color left
  14. // next color left
  15. // current color right
  16. // next color right
  17. var colorIndices = [0,1,2,3];
  18. //transition speed
  19. var gradientSpeed = 0.002;
  20. updateGradient(selector,step,colors,colorIndices,gradientSpeed);
  21. }
  22. function updateGradient(selector,step,colors,colorIndices,gradientSpeed){
  23. if ( $===undefined ) return;
  24.  
  25. var c0_0 = colors[colorIndices[0]];
  26. var c0_1 = colors[colorIndices[1]];
  27. var c1_0 = colors[colorIndices[2]];
  28. var c1_1 = colors[colorIndices[3]];
  29.  
  30. var istep = 1 - step;
  31. var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
  32. var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
  33. var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
  34. var color1 = "rgb("+r1+","+g1+","+b1+")";
  35.  
  36. var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
  37. var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
  38. var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
  39. var color2 = "rgb("+r2+","+g2+","+b2+")";
  40.  
  41. $(selector).css({
  42. background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({
  43. background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});
  44.  
  45. step += gradientSpeed;
  46. if ( step >= 1 )
  47. {
  48. step %= 1;
  49. colorIndices[0] = colorIndices[1];
  50. colorIndices[2] = colorIndices[3];
  51.  
  52. //pick two new target color indices
  53. //do not pick the same as the current one
  54. colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
  55. colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
  56. }
  57. }
  58. // ========================================================================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement