Change the background gradient of a page when moving the mouse

I have a page with the gradient used when loading the page through CSS, and I would like to animate the page by alternating the colors of the gradient and the degree (linear gradient - 4 different colors, all worsening to white) when moving the mouse. If I use only 2 colors, it works fine. But I want to get a random color from the array when moving the mouse, but it flickers. Any solution for this?

Here is my fiddle

var colorArr = ['#dfa7ca', '#f7c2b3', '#bae0f1', '#a6d6cb'];
var grFrom = colorArr[Math.floor(Math.random()*colorArr.length)];
var grTo = '#FFFFFF';

$("body").mousemove(function( e ) {
  var x = e.pageX - this.offsetLeft;
  var y = e.pageY - this.offsetTop;
  var grFrom = colorArr[Math.floor(Math.random()*colorArr.length)];//get a new random color
  var xy = (x + y) / 8;
  var w = $(this).width(),
  pct = 360*(+e.pageX)/w,
  bg = "linear-gradient(" + xy + "deg,"+grFrom+","+grTo+")";
  $("body").css("background-image", bg);
});
+4
source share
2 answers

You can wrap the handler in _. throttle and play with millions until you get an acceptable result.

var colorArr = ['#dfa7ca', '#f7c2b3', '#bae0f1', '#a6d6cb'];
var grFrom = colorArr[Math.floor(Math.random()*colorArr.length)];
var grTo = '#FFFFFF';


var wrapped = _.throttle(function(e){
  var x = e.pageX - this.offsetLeft;
  var y = e.pageY - this.offsetTop;
  var grFrom = colorArr[Math.floor(Math.random()*colorArr.length)];
  var xy = (x + y) / 8;
  var w = $(this).width(),
  pct = 360*(+e.pageX)/w,
  bg = "linear-gradient(" + xy + "deg,"+grFrom+","+grTo+")";
  $("body").css("background-image", bg);
},50)//Try increasing/decreasing this value to see the differrence


$("body").mousemove(wrapped);

See: https://jsfiddle.net/g137be71/24/

: . throttle. https://jsfiddle.net/g137be71/82/

0

, jQueryUI, animate() . , :

https://jqueryui.com/animate/

, - :

 $( "#selector" ).animate({
          backgroundColor: bg
        }, 10 );
0

Source: https://habr.com/ru/post/1696054/


All Articles