渐变跟随鼠标但没有赶上

时间:2019-02-25 15:12:32

标签: javascript jquery gradient mousemove

我整理了一个简单的jQuery脚本来创建一个径向渐变,该渐变在鼠标后面具有延迟,但是由于它是在mousemove函数中,因此当鼠标停止移动时,渐变不会赶上。当鼠标停止而不编写持续运行的功能时,有没有一种简单的方法可以使渐变赶上鼠标?

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>

1 个答案:

答案 0 :(得分:1)

您可以使用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>