SVG< g>元素拖动导致使用d3的闪烁问题 [英] SVG <g> element dragging causes flickering issue using d3
问题描述
我一直在尝试通过转换转换将d3库用于dvg元素的拖放.我能够拖动一个元素,但是拖动时它会闪烁.
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.
口吃"使用d3.behavior.drag()时拖动并进行变换
D3 .js:使用origin()函数按组中包含的元素拖动组('g')中的所有内容
对于最后一个链接,我认为我无法理解导致此问题的svg结构的必要性.有人可以在这里帮助我吗?
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?
推荐答案
为此,更容易使用d3.event
而不是d3.mouse
.这是使用.data()
的d3样式的方法:
It is easier to use d3.event
instead of d3.mouse
for this. Here is a d3 style approach with .data()
:
- 在源svg中读取
<g>
的translate
属性. - 将
translate
的x和y值添加到d3对象的data
. - 在拖动事件期间调整
<g>
的data
和translate
.
- Read out the
translate
attribute of the<g>
in your source svg. - Add the x and y value of the
translate
to thedata
of the d3 object. - Adjust the
data
and thetranslate
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>
这篇关于SVG< g>元素拖动导致使用d3的闪烁问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!