[英]Page background gradient change on mouse move
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. 我有一个页面,通过CSS在页面加载时应用渐变,并希望在鼠标移动时交替使用渐变颜色和度数(线性渐变 - 4种不同颜色都降低为白色)的页面设置动画。 If I use only 2 colors it works fine.
如果我只使用2种颜色就行了。 But I want to get a random color from an array on mouse move but it flickers.
但我希望在鼠标移动时从阵列中获得随机颜色,但它会闪烁。 Any solution for that?
任何解决方案?
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. 我认为你需要包含jQueryUI,然后你可以使用
animate()
来改变颜色。 Please check here: 请点击这里:
https://jqueryui.com/animate/ https://jqueryui.com/animate/
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. 您可以将处理程序包装在_.throttle中 ,然后使用millis,直到获得可接受的结果。
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/ 请参阅: https : //jsfiddle.net/g137be71/24/
Update: Actually I had pasted a wrong link. 更新:实际上我粘贴了一个错误的链接。 This is for
throttle
. 这是
throttle
。 https://jsfiddle.net/g137be71/82/ https://jsfiddle.net/g137be71/82/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.