gpt4 book ai didi

javascript - 渐变跟随鼠标但没有 catch

转载 作者:行者123 更新时间:2023-11-29 15:10:39 29 4
gpt4 key购买 nike

我已经编写了一个简单的 jQuery 脚本来创建一个延迟跟随鼠标的径向渐变,但是由于它在 mousemove 函数中,当鼠标停止移动时渐变不会跟上来。有没有一种简单的方法可以让渐变在鼠标停止时 catch 鼠标,而无需编写一个不断运行的函数?

var xPos = 0;
var yPos = 0;
var dX = 0;
var dY = 0;
var repeater;

$(document).mousemove(function(event) {
windowWidth = $(window).width();
windowHeight = $(window).height();
mouseXpercentage = Math.round(event.pageX / windowWidth * 100);
mouseYpercentage = Math.round(event.pageY / windowHeight * 100);

dX = mouseXpercentage - xPos;
dY = mouseYpercentage - yPos;

xPos += (dX / 50);
yPos += (dY / 50);

$('.rgradient').css('background', 'radial-gradient(at ' + xPos + '% ' + yPos + '%, #e6e6e6, #1e1e1e)');
});
.rgradient {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background: #1e1e1e;
background: radial-gradient( at center, #e6e6e6 #1e1e1e);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="rgradient"></div>

最佳答案

您可以使用 requestAnimationFrame() ,因为它每帧只运行一次:

var xPos = 0;
var yPos = 0;
var dX = 0;
var dY = 0;
var mouseRaf = null;
var gradMoveRaf = null;

$(document).mousemove(function(event) {
if (!mouseRaf) {
mouseRaf = requestAnimationFrame(function() {
windowWidth = $(window).width();
windowHeight = $(window).height();

mouseXpercentage = Math.round(event.pageX / windowWidth * 100);
mouseYpercentage = Math.round(event.pageY / windowHeight * 100);

dX = mouseXpercentage - xPos;
dY = mouseYpercentage - yPos;

mouseRaf = null;
});
}

if (!gradMoveRaf) {
gradMoveRaf = requestAnimationFrame(gradMove);
}
});

function gradMove() {
xPos += (dX / 50);
yPos += (dY / 50);

$('.rgradient').css('background', 'radial-gradient(at ' + xPos + '% ' + yPos + '%, #e6e6e6, #1e1e1e)');

var absX = Math.abs(mouseXpercentage - xPos);
var absY = Math.abs(mouseYpercentage - yPos);

if (absX < 1 && absY < 1) {
gradMoveRaf = null;
console.log("stop");
} else {
gradMoveRaf = requestAnimationFrame(gradMove);
console.log("repeat");
}
}
.rgradient {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background: #1e1e1e;
background: radial-gradient(at center, #e6e6e6 #1e1e1e);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="rgradient"></div>

关于javascript - 渐变跟随鼠标但没有 catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54869243/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com