简体   繁体   English

相对于鼠标 position 从其中心缩放图像

[英]Scale image relative to mouse position from its center

Hello my dear fellows,亲爱的小伙伴们好,

I've been trying to recreate the effect: image scales up as the mouse get closer to the center of the image found on https://www.davidwilliambaum.com/我一直在尝试重新创建效果:当鼠标靠近https://www.davidwilliambaum.com/上找到的图像中心时,图像会放大

I have been very unsuccessfull so far, as I am not sure how to approach the problem.到目前为止,我一直很不成功,因为我不知道如何解决这个问题。

I started a codepen with some ideas: https://codepen.io/dindon-studio/pen/RwLwRKM我用一些想法开始了一个codepen: https://codepen.io/dindon-studio/pen/RwLwRKM

As you can see I first get the center coordinate of the image, and then i try some dirty formula to scales it up with the mouse distance.正如你所看到的,我首先得到了图像的中心坐标,然后我尝试了一些肮脏的公式来用鼠标距离放大它。 But it is very buggy and not convincing at all.但它非常有问题,根本没有说服力。

Does anyone got a better approach?有没有人有更好的方法? Deep thanks for you help!深深感谢您的帮助!

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",});

  }
 });

I build off from your codepen and made some adjustments: https://codepen.io/Mookiie/pen/qBPBmNe我从您的 codepen 构建并进行了一些调整: https://codepen.io/Mookiie/pen/qBPBmNe

The higher the scalingFactor the closer the mouse needs to be for a size change. 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)
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM