Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: 97a23e1b13d731afc868b8816ed363c07604ed6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import getComputedTransformMatrix from './utils.js';

function zoomIn(deltaY) {
  return deltaY < 0;
}

function getScale(e, factor) {
  return zoomIn(e.deltaY) ? 1 + factor : 1 - factor;
}

function getFocalPointBeforeTransform(el, e) {
  const { x, y, width, height } = el.getBoundingClientRect();

  return {
    x: e.clientX,
    y: e.clientY,
    relativeToImageSize: {
      x: (e.clientX - x) / width,
      y: (e.clientY - y) / height
    }
  };
}

function getFocalPointAfterTransform(el, fpBeforeTrans) {
  const { x, y, width, height } = el.getBoundingClientRect(),
    relativeFocalPoint = fpBeforeTrans.relativeToImageSize;

  return {
    x: x + width * relativeFocalPoint.x,
    y: y + height * relativeFocalPoint.y
  };
}

function getTranslateMatrix(el, e, scaleMatrix) {
  const fpBeforeTrans = getFocalPointBeforeTransform(el, e);

  el.style.transform = scaleMatrix;

  const fpAfterTrans = getFocalPointAfterTransform(el, fpBeforeTrans),
    translateMatrix = new DOMMatrix();

  return translateMatrix.translate(
    fpBeforeTrans.x - fpAfterTrans.x,
    fpBeforeTrans.y - fpAfterTrans.y
  );
}

export default function (el, e, factor = 0.1) {
  e.preventDefault();

  const mtx = getComputedTransformMatrix(el),
    scale = getScale(e, factor),
    transMtx = getTranslateMatrix(el, e, mtx.scale(scale));

  el.style.transform = transMtx.multiply(mtx).scale(scale);
}