【问题标题】:Scale image relative to mouse position from its center相对于鼠标位置从其中心缩放图像
【发布时间】:2022-01-06 12:49:50
【问题描述】:

亲爱的小伙伴们好,

我一直在尝试重新创建效果:当鼠标靠近https://www.davidwilliambaum.com/ 上的图像中心时,图像会放大

到目前为止,我一直很不成功,因为我不知道如何解决这个问题。

我用一些想法开始了一个 codepen:https://codepen.io/dindon-studio/pen/RwLwRKM

如您所见,我首先获取图像的中心坐标,然后尝试使用一些肮脏的公式来根据鼠标距离将其放大。 但它非常有缺陷,根本没有说服力。

有人有更好的方法吗? 非常感谢您的帮助!

var mX, mY, distance, element
element = $('.project')

function calculateDistance(elem, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)), 2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2))); }

$(document).mousemove(function(e) {  
mX = e.pageX;
mY = e.pageY;
distance = calculateDistance(element, mX, mY);
if (distance< 500 && distance >50){
   var scaling = 1 + (1/distance) *100

  gsap.to(".project", {duration: 0.01, scale: scaling,ease: "power2.in",});

  }
 });

【问题讨论】:

  • 一个问题是图像中心的位置一直在重新计算——尽管实际上它是固定的。在开始时计算并使用这些值。这停止了​​“抖动”。我没有提出 sn-p 因为我不知道你想要的比例因子是什么。
  • 确保使用overwrite: true"auto" 来杀死之前的补间。

标签: javascript jquery css frontend gsap


【解决方案1】:

我在你的 codepen 基础上做了一些调整:https://codepen.io/Mookiie/pen/qBPBmNe

scalingFactor 越高,鼠标需要越靠近才能更改大小。

function calculateCenter(image) {
  var rect1 = image.getBoundingClientRect();
  var x = rect1.left + rect1.width * 0.5;
  var y = rect1.top + rect1.height * 0.5;
  return { x: x, y: y }
}

function getDistance(x1, y1, x2, y2){
  let y = x2 - x1;
  let x = y2 - y1;

  return Math.sqrt(x * x + y * y);
}

function distanceFromCenter(image, mouseX, mouseY) {
  var imageCenter = calculateCenter(image);
  return getDistance(imageCenter.x, imageCenter.y, mouseX, mouseY)
}

function adjustImage(image, mX, mY) {
    var distance = distanceFromCenter(image, mX, mY);

    const baseScale = 1
    const maxScaling = 1.5;
    const scalingFactor = 1;
    
    const adjustedScaling = maxScaling - ((distance / 1000) * scalingFactor)
    const scaling = adjustedScaling >= baseScale ? adjustedScaling : baseScale
 
    gsap.to(image, {duration: 0.01, scale: scaling, ease: "power2.in",});
}


  $(document).mousemove(function(e) {  
    const mX = e.pageX;
    const mY = e.pageY;
    const images = $("img")
    
    images.each(function() {
      adjustImage(this, mX, mY)
    })
});

【讨论】:

  • 该死!马尔科姆!非常感谢, const scaling =adjustedScaling >= baseScale ? adjustedScaling:baseScale 是明智之举。祝您有美好的一天!
猜你喜欢
  • 2014-04-22
  • 2012-10-20
  • 2015-07-12
  • 2017-02-11
  • 1970-01-01
  • 2020-09-07
  • 2016-04-14
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多