SVG <g> element dragging causes flickering issue using d3

两盒软妹~` 提交于 2020-01-16 19:46:46

问题


I have been trying to use d3 library for drag n drop of dvg element by using transform translate. I am able to drag an element but it flickers while dragging.

I have been searching and doing trial and error so far from below links but it doesn't help me.

"Stuttering" drag when using d3.behavior.drag() and transform

D3.js: Dragging everything in group ('g') by element contained in the group using origin() function

How to drag an svg group using d3.js drag behavior?

For the last link, I think I am not able to understand the necessity of svg structure for this requirement which causes this issue. Can anyone help me here?


回答1:


It is easier to use d3.event instead of d3.mouse for this. Here is a d3 style approach with .data():

  1. Read out the translate attribute of the <g> in your source svg.
  2. Add the x and y value of the translate to the data of the d3 object.
  3. Adjust the data and the translate of the <g> during the drag event.

function bindDragging() {

    // Define d3 object
    var g = d3.select("#group");

    // Get translate (from: https://stackoverflow.com/a/38230545/3620572)
    var elem = document.createElementNS("http://www.w3.org/2000/svg", "g");
    elem.setAttributeNS(null, "transform", g.attr("transform"));
    var matrix = elem.transform.baseVal.consolidate().matrix;
    var x = matrix.e;
    var y = matrix.f;

    g.data([{
        // Position of the group
        x: x,
        y: y
        }])
        .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragend)
        );

    function dragstarted(d) {
        g.selectAll("rect").classed("active", true);
    }

    function dragged(d) {
        // Set the new position
        d.x += d3.event.dx;
        d.y += d3.event.dy;
        d3.select(this).attr("transform", function (d) {
            return "translate(" + [d.x, d.y] + ")"
        });

    }

    function dragend(d) {
        g.selectAll("rect").classed("active", false);
    }
}
bindDragging();
#group {
    stroke-width: 3;
    stroke: #808080;
    cursor: -webkit-grab;
    cursor: grab;
}

.active {
    stroke: #ff0000;
    cursor: -webkit-grabbing;
    cursor: grabbing;
}
<div class="svgContainer">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 776.63 680.09">
    <g id="group" transform="translate(0, 0)">
        <rect width="100" height="50" style="fill:rgb(40, 40, 109);" />
        <rect width="100" height="50" y="50" style="fill:rgb(63, 149, 75);" />
    </g>
</svg>
</div>
<script src="https://d3js.org/d3.v4.min.js"></script>


来源:https://stackoverflow.com/questions/49994438/svg-g-element-dragging-causes-flickering-issue-using-d3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!