Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: 834602b3cd1f3890e7c4a2648a0c89892cdf80b2 (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
63
64
65
66
67
import getComputedTransformMatrix from './utils.js';

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

function getScale(e, factor) {
  const outMult = 1 - factor;
  const inMult = 1 + factor / outMult

  return zoomIn(e.deltaY) ? inMult : outMult;
}

function getFocalPointBeforeTransform(el, e, inverseScreenCTM) {
  const { x, y, width, height } = el.getBoundingClientRect();
  const pointer = (new DOMPoint(e.clientX, e.clientY)).matrixTransform(inverseScreenCTM);
  const origin = (new DOMPoint(x, y)).matrixTransform(inverseScreenCTM);
  const 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();
  const origin = (new DOMPoint(x, y)).matrixTransform(inverseScreenCTM);
  const terminus = (new DOMPoint(x + width, y + height)).matrixTransform(inverseScreenCTM);
  const 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();
  const fpBeforeTrans = getFocalPointBeforeTransform(el, e, inverseScreenCTM);

  el.style.transform = scaleMatrix;

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

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

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

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

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