Javascript 如何在 D3 中移动 SVG 的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28232333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:25:22  来源:igfitidea点击:

How to move SVG's position in D3?

javascriptsvgd3.js

提问by Photunix

I created a svg using D3. However, it only shows up on the upper left conner of the screen, or been appended to another svg. Are there anyway I can move it using JavaScript? For example:

我使用 D3 创建了一个 svg。然而,它只显示在屏幕的左上角,或者被附加到另一个 svg。无论如何我可以使用JavaScript移动它吗?例如:

  var svg = d3.select("body").append("svg")
    .attr("width", 200)
    .attr("height", 200);

回答by Hugolpz

Using d3js + Jquery :

使用 d3js + Jquery :

// svg design
var svg = d3.select("#chart").append("svg")
    .attr("width", 200)
    .attr("height", 200);

// svg repositioning
$("svg").css({top: 200, left: 200, position:'absolute'});

Or

或者

// svg align center
d3.select("#chart").attr("align","center"); //  thanks & +1 to chaitanya89

Live demo

现场演示

回答by chaitanya89

Instead of appending SVG to the body, append it to a html element like <div>and add style to it.

不是将 SVG 附加到正文,而是将其附加到一个 html 元素,例如<div>并为其添加样式。

Javascript:

Javascript:

var svg = d3.select("#chart").append("svg")
.attr("width", 200)
.attr("height", 200);

HTML: add this to your body tag.

HTML:将此添加到您的 body 标签中。

<div id="chart" align="center"></div>

If you want to align svg using javascript, remove alignattribute in the above <div>tag and add the following in your javascript.

如果您想使用 javascript 对齐 svg,请删除align上述<div>标签中的属性并在您的 javascript 中添加以下内容。

document.getElementById("chart").align = "center";

Alternatively, You could also do it using D3.

或者,您也可以使用 D3 来完成。

d3.select("#chart")
.attr("align","center");

回答by Fernando Santucci

Before you need append any SVG object to apply the transition on canvas.

在您需要附加任何 SVG 对象以在画布上应用过渡之前。

The tutorial step-by-step below show you, in practice, each property of method Transition from D3js.

下面的教程逐步向您展示了 D3js 方法 Transition 在实践中的每个属性。

http://blog.visual.ly/creating-animations-and-transitions-with-d3-js/

http://blog.visual.ly/creating-animations-and-transitions-with-d3-js/

Enjoy!

享受!

回答by Vishnu Prasanth

Use negative value in margin.

在保证金中使用负值。

margin = { top: 20, right: -600, bottom: 20, left: 640 }

边距 = { 顶部:20,右侧:-600,底部:20,左侧:640 }

The content is added on the left by default. To shift to right, use negative margins. following line will take it to the second right half of the screen.

内容默认添加在左侧。要向右移动,请使用负边距。以下行将其带到屏幕的右后半部分。