Is it possible to optimize this formula?

62 Views Asked by At

The given formula arranges the contents of the container according to the mouse movement.. the problem was in the size of the image, and in the fact that approaching along the x and y axes from different sides, the arrangement was calculated differently.

const zoomEffect = (event: any) => {
    setZoomMode(true);
    const xa = event.pageX-containerRef.current.offsetLeft;
    const xb = containerRef.current.offsetWidth;
    const xc = zoomRef.current?.getBoundingClientRect().width;
    const ya = event.pageY-containerRef.current.offsetTop;
    const yb = containerRef.current.offsetHeight;
    const yc = zoomRef.current?.getBoundingClientRect().height;
    setMouseCoords({
      x: xc ? -(xa)/(xb/((xc)-xb)) : 0,
      y: yc ? -(ya)/(yb/((yc)-yb)) : 0,
    });
  };

<div ref={conteinerRef} onMouseMove={zoomEffect}>
  <div style={{
    left: mouseCoords.x,
    top: mouseCoords.y,
  }}>
    <Img ref_={zoomRef} />
  </div>}
</div>
1

There are 1 best solutions below

0
Thomas On

I don't know about the correctness of the formula, that's up to you, but I find it very confusing and convoluted with all these 2 letter variables.

I'd write it like this:


const zoomEffect = (event: any) => {
  setZoomMode(true);

  const { offsetLeft, offsetTop, offsetWidth, offsetHeight } = conteinerRef.current;
  const { width = 0, height = 0 } = zoomRef.current?.getBoundingClientRect() || {};

  setMouseCoords({
    x: width ? (offsetLeft - event.pageX) * (width - offsetWidth) / offsetWidth : 0,
    y: height ? (offsetTop - event.pageY) * (height - offsetHeight) / offsetHeight : 0
  });
};

The transforms, how I got from your form to mine.

  1. ((xc)-xb) === (xc-xb)
  2. a/(b/c) === a*c/b
  3. -(xa) and xa === a-b -> -xa === b-a or (containerRef.current.offsetLeft - event.pageX)