Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: 24ddb7968f4e972122ed16fb5bae8577c0d3493e (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
const zoomStepRatio = 0.25,
  positive = 1,
  negative = -1;

function toLocalCoords(svg, x, y) {
  const clientP = new DOMPoint(x, y);

  return clientP.matrixTransform(svg.getScreenCTM().inverse());
}

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

function calcSizeChangeAmounts(width, height) {
  return {
    width: width * zoomStepRatio,
    height: height * zoomStepRatio
  };
}

function calcValChangeRatios(focusPoint, x, y, width, height) {
  return {
    x: (focusPoint.x - x) / width,
    y: (focusPoint.y - y) / height,
    width: (width + x - focusPoint.x) / width,
    height: (height + y - focusPoint.y) / height
  };
}

function calcValChangeAmounts(focusPoint, x, y, width, height) {
  const changeAmount = calcSizeChangeAmounts(width, height),
    valChangeRatio = calcValChangeRatios(focusPoint, x, y, width, height);

  return {
    x: valChangeRatio.x * changeAmount.width,
    y: valChangeRatio.y * changeAmount.height,
    width: valChangeRatio.width * changeAmount.width,
    height: valChangeRatio.height * changeAmount.height
  };
}

export default function (svg, e) {
  const pointerPosition = toLocalCoords(svg, e.clientX, e.clientY),
    sign = zoomIn(e.deltaY) ? positive : negative,
    { x, y, width, height } = svg.viewBox.baseVal,
    changeAmount = calcValChangeAmounts(pointerPosition, x, y, width, height),

    attr = {
      x: x + sign * changeAmount.x,
      y: y + sign * changeAmount.y,
      width: width + sign * (-changeAmount.x - changeAmount.width),
      height: height + sign * (-changeAmount.y - changeAmount.height)
    };

  return `${attr.x} ${attr.y} ${attr.width} ${attr.height}`;
}