Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: fc0540ba238bef05844a503d8b47a097a084e7f6 (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
57
58
59
60
61
62
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, inverseScreenCTM) {
  const { x, y, width, height } = el.getBoundingClientRect(),
    pointer = (new DOMPoint(e.clientX, e.clientY)).matrixTransform(inverseScreenCTM),
    origin = (new DOMPoint(x, y)).matrixTransform(inverseScreenCTM),
    terminus = (new DOMPoint(x + width, y + height)).matrixTransform(inverseScreenCTM);

  return {
    x: pointer.x,
    y: pointer.y,
    relativeToImageSize: {
      x: (pointer.x - origin.x) / (terminus.x - origin.x),
      y: (pointer.y - origin.y) / (terminus.y - origin.y)
    }
  };
}

function getFocalPointAfterTransform(el, fpBeforeTrans, inverseScreenCTM) {
  const { x, y, width, height } = el.getBoundingClientRect(),
    origin = (new DOMPoint(x, y)).matrixTransform(inverseScreenCTM),
    terminus = (new DOMPoint(x + width, y + height)).matrixTransform(inverseScreenCTM),
    relativeFocalPoint = fpBeforeTrans.relativeToImageSize;

  return {
    x: origin.x + (terminus.x - origin.x) * relativeFocalPoint.x,
    y: origin.y + (terminus.y - origin.y) * relativeFocalPoint.y
  };
}

function getTranslateMatrix(el, e, scaleMatrix) {
  const inverseScreenCTM = el.getScreenCTM().inverse(),
    fpBeforeTrans = getFocalPointBeforeTransform(el, e, inverseScreenCTM);

  el.style.transform = scaleMatrix;

  const fpAfterTrans = getFocalPointAfterTransform(el, fpBeforeTrans, inverseScreenCTM),
    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 = mtx.multiply(transMtx).scale(scale);
}