Web Dev Solutions

Catalin Mititiuc

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); } }