问题
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():
- Read out the
translateattribute of the<g>in your source svg. - Add the x and y value of the
translateto thedataof the d3 object. - Adjust the
dataand thetranslateof 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