Constantly moving an object using translateX inside the parent, what's wrong with my calculation?

Viewed 22

I'm using Anime.js (but I think it's not relevant) which constantly call my function computeMinMaxTranslateX for moving target inside the parent, without overflowing.

My assumption is that:

  • The translateX minimum value is given by target x offset minus container x offset
  • The translateX maximum value is given by container width minus element width minus element x offset (bacause the previous position should be taken into account)

Is there something wrong with my reasoning? It's not working, the target is overflowing the container. Here is the function i wrote:

const computeMinMaxTranslateX = (element, container) => {
  const {
    x: elementX,
    width: elementWidth,
  } = element.getBoundingClientRect();
  const {
    x: containerX,
    width: containerWidth,
  } = container.getBoundingClientRect();

  return {
    min: -(elementX - containerX),
    max: containerWidth - (elementX - containerX) - elementWidth
  };
};

Explanation of the problem Example

0 Answers
Related