简体   繁体   English

使用d3在HTML中修改SVG

[英]Modifying an SVG in HTML using d3

this is my first post so I'll try to make sure I'm following appropriate posting etiquette. 这是我的第一篇文章,所以我会尽力确保我遵循适当的帖子礼仪。

I have no experience whatsoever with html, d3, or javascript. 我对html,d3或javascript没有任何经验。 I do however have some exposure to xml and svg. 但我确实有一些xml和svg的曝光。 I'm trying to work through this tutorial: [ http://bost.ocks.org/mike/circles/] . 我正在尝试完成本教程:[ http://bost.ocks.org/mike/circles/] I spent several hours yesterday fruitlessly attempting to complete the first step, which is to change the color and radius of the three circles using d3.selectAll(). 我花了几个小时昨天毫无结果地试图完成第一步,即使用d3.selectAll()改变三个圆圈的颜色和半径。 I've read through several posts on here and looked at other tutorials but I cannot for the life of me make the circles blue. 我已经阅读了这里的几篇文章并查看了其他教程,但我不能为我的生活让圈子变蓝。 Unfortunately the tutorial never shows the entirety of their code. 不幸的是,教程永远不会显示他们的全部代码。 I've been able to display the three black circles (original svg) in my browser but can't seem to get d3 to select them and carry out the changes. 我已经能够在我的浏览器中显示三个黑色圆圈(原始svg),但似乎无法让d3选择它们并执行更改。 I'm not even sure if the xml is embedded within the html or if it is external and read in somehow. 我甚至不确定xml是否嵌入在html中,或者它是否是外部的并以某种方式读取。

Could someone post the html you would use to do this? 有人可以发布您用来做这个的HTML吗? Any assistance would be greatly appreciated. 任何帮助将不胜感激。

Here is the xml corresponding to the circles: 这是与圆圈对应的xml:

<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
 <circle cx="80" cy="60" r="10"></circle>
  <circle cx="120" cy="60" r="10"></circle>
</svg>

And here is the code to make the changes: 以下是进行更改的代码:

var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);

Your code is correct. 你的代码是正确的。 I'm guessing you aren't putting it together correctly. 我猜你没有正确地把它放在一起。 Here's the shortest example: 这是最简短的例子:

 <!DOCTYPE html> <html> <head> <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script> </head> <body> <svg width="720" height="120"> <circle cx="40" cy="60" r="10"></circle> <circle cx="80" cy="60" r="10"></circle> <circle cx="120" cy="60" r="10"></circle> </svg> <script> var circle = d3.selectAll("circle"); circle.style("fill", "steelblue"); circle.attr("r", 30); </script> </body> </html> 

Your code looks good, there must be another issue. 你的代码看起来很好,必须有另一个问题。 Take a look at this fiddle to demonstrate what should happen. 看看这个小提琴来演示应该发生什么。 Ignore the transition/duration/delay, that's just to slow everything down so it's easily visible. 忽略转换/持续时间/延迟,这只是为了减慢一切,所以它很容易看到。

http://jsfiddle.net/s6u5my8k/ http://jsfiddle.net/s6u5my8k/

var circle = d3.selectAll('circle')
    .transition().duration(750).delay(750)
    .style('fill', 'steelblue')
    .attr('r', 30);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM