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?
It is easier to use d3.event
instead of d3.mouse
for this. Here is a d3 style approach with .data()
:
translate
attribute of the <g>
in your source svg. translate
to the data
of the d3 object. 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 dx += d3.event.dx; dy += d3.event.dy; d3.select(this).attr("transform", function (d) { return "translate(" + [dx, dy] + ")" }); } 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.