I have a page with a gradient applied on page load via CSS and would like to animate the page alternating the gradient colors and degree (linear-gradient - 4 different colors all degrade to white) on mouse move. If I use only 2 colors it works fine. But I want to get a random color from an array on mouse move but it flickers. Any solution for that?
Here's 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);
});
I think you need to inlcude jQueryUI and then you can use animate()
to change the color. Please check here:
So you should use something like this:
$( "#selector" ).animate({
backgroundColor: bg
}, 10 );
You can wrap your handler in _.throttle , and play with the millis, until you have 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/
Update: Actually I had pasted a wrong link. This is for throttle
. https://jsfiddle.net/g137be71/82/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.