Make divs towards cursor

Comparing some of the previous answers, I was able to have multiple div elements rotating in the 3D cursor (similar behavior as eyes). However, there are still some small bugs:

  • at a certain moment, moving the cursor horizontally, the shadows will "break" and move
  • If the cursor is placed in the middle of all 4 elements, I would expect symmetrical behavior. However, it is not...

Can someone help me on this please?

Here's the code (and a pen: http://codepen.io/anon/pen/pJROyL )

$(document).ready(function() {
  var browserPrefix = "",
    usrAg = navigator.userAgent;
  if (usrAg.indexOf("Chrome") > -1 || usrAg.indexOf("Safari") > -1) {
    browserPrefix = "-webkit-";
  } else if (usrAg.indexOf("Opera") > -1) {
    browserPrefix = "-o";
  } else if (usrAg.indexOf("Firefox") > -1) {
    browserPrefix = "-moz-";
  } else if (usrAg.indexOf("MSIE") > -1) {
    browserPrefix = "-ms-";
  }

  $(document).mousemove(function(event) {

    $('.box').each(function() {
      elOffset = $(this).offset();
      elWidth = $(this).width();
      elHeight = $(this).height();
      elCenterX = elOffset.left + elWidth / 2;
      elCenterY = elOffset.top + elHeight / 2;

      dx = event.pageX - elCenterX;
      dy = event.pageY - elCenterY;
      tiltx = Math.min((dy / elCenterY), 1);
      tilty = -Math.min((dx / elCenterX), 1);
      radius = Math.sqrt(Math.pow(tiltx, 2) + Math.pow(tilty, 2));
      degree = (radius * 30);

      shadx = degree * tiltx;
      shady = degree * tilty;

      $(this).css(browserPrefix + 'transform', 'rotate3d(' + tiltx + ', ' + tilty + ', 0, ' + degree + 'deg)');
      if (dx > elCenterX) {
        $(this).css('box-shadow', +(-shady) + 'px ' + (-shadx) + 'px 5px #3D352A');

      } else {
        $(this).css('box-shadow', +shady + 'px ' + (-shadx) + 'px 5px #3D352A');
      }
    });
  });
});

      

+3


source to share


1 answer


For a symmetric problem, the solution should shift half the body width:

bodyHalfWidth = $('body').width()/2;
// ... More code ...
tilty = -Math.min(dx / (elCenterX  + bodyHalfWidth), 1);

      

This diminishes the effect, so I add a gain constant.

bodyHalfWidth = $('body').width()/2;
gain = 2;
// ... More code ...
tilty = -Math.min(gain*dx / (elCenterX  + bodyHalfWidth), 1);

      




(EDIT: Another subquery solution by George Lee posted here also to consolidate the general answer)

To fix shadow splitting, remove the last if statement if(dx > elCenterX)

and leave only$(this).css('box-shadow', +shady + 'px ' + (-shadx) + 'px 5px #3D352A');

0


source







All Articles