Interact.js: 使用 ViewBox 时拖动 SVG 元素

Interact.js: dragging SVG element when using ViewBox

我正在构建一个应用程序,我希望在其中同时使用 SVG 和 interact.js 来拖放 SVG 元素。我的 SVG 使用 ViewBox 以便在不同分辨率下正确缩放图形,但问题是当我拖动时,鼠标移动 "faster" 而不是它移动的元素。

我知道这是屏幕坐标系和 SVG 之间的问题,我在这里找到了答案:

但是,我不知道如何将上面 link 处标记的答案与我的代码联系起来。我尝试的每一件不同的事情都会导致更奇怪的行为。我正在尝试将其集成到 interact.js 网站上提供的拖放示例中:

interact('.draggable')
    .draggable({
        // enable inertial throwing
        inertia: true,
        // keep the element within the area of it's parent
        restrict: {
            restriction: "parent",
            endOnly: true,
            elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
        },
        // enable autoScroll
        autoScroll: true,

        // call this function on every dragmove event
        onmove: dragMoveListener,
        // call this function on every dragend event
        onend: function (event) {
            //removed this code for my test
        }
    });

function dragMoveListener (event) {
    var target = event.target,
        // keep the dragged position in the data-x/data-y attributes
        x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
        y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

    // translate the element
    target.style.webkitTransform =
    target.style.transform =
          'translate(' + x + 'px, ' + y + 'px)';

    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
}

我设法得到的最接近的是用此代码代替上面的 dragMoveListener

function dragMoveListener(event) {
    var target = event.target;

    var svg = document.querySelector('svg');
    var svgRect = svg.getBoundingClientRect();
    var ctm = target.getScreenCTM();
    var point = svg.createSVGPoint();
    var point2;

    point.x = event.clientX;
    point.y = event.clientY;

    point2 = point.matrixTransform(ctm);

    var x = point2.x;
    var y = point2.y;

    // translate the element
    target.style.webkitTransform =
        target.style.transform =
        'translate(' + x + 'px, ' + y + 'px)';

    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
}

但这会导致元素离鼠标很远,尽管它 几乎 同步移动(似乎仍然有点偏离)。我怎样才能让它工作,我可能对基于我上面的 "almost" 解决方案的 linked 问题中提出的解决方案有什么误解?

这里是相关的HTML。所有设置仅用于测试目的,可能不是最终的(例如 2000 和 4000 可能比我最终需要的要大)。

<svg id="svgArea" style="width:100%; border: 1px solid black" viewBox="0 0 2000 4000">
    <rect id="item" width="100" height="200" stroke="#000000" stroke-width="5" fill="#ff0000" class="draggable" ></rect>
</svg>

这里是拖动旋转使用适当的 SVG 到 DOM 坐标转换的工作片段:

Codepen drag rotate snippet

这尤其是你所缺少的:

  mouse.x = event.clientX;
  mouse.y = event.clientY;
  mouse = mouse.matrixTransform(mainSVG.getScreenCTM().inverse());

因此,在您的情况下,您应该从 svgArea 元素中获取 CTM。