0

I want to change SVG somen element attibutes using d3. Actually I will be downloading via AJAX from server data that will change SVG element colors based on data values.

Here is my piece of code to change SVG element graphical behaviour:

SVG EXAMPLE FILE:

<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
 <!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
 <g>
  <title>Layer 1</title>
  <rect id="box1" height="54" width="106" y="73" x="53" stroke-width="2" stroke="#000000" fill="#FF0000"/>
  <ellipse ry="39" rx="41" id="circle1" cy="103" cx="246" stroke-width="2" stroke="#000000" fill="#FF0000"/>
  <path id="multiline1" d="m395,105l70,10c0,0 11,63 11,64c0,1 -3,60 -9,61c-6,1 -75,1 -79,1c-4,0 -43,-16 -42,-25c1,-9 -4,-29 1,-42c5,-13 14,-57 14,-58" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="2" stroke="#000000" fill="#FF0000"/>
 </g>
</svg>

HTML Code:

<script src="~/Scripts/d3-master/d3.min.js" charset="utf-8"></script>

<object id="svgobject" type="image/svg+xml" data=".\svg\mainscreen.svg">
</object>

<script type="text/javascript">

    var element = d3.selectAll("svgobject");
    var item = element.property("box1");
    item.style("color", "blue");

</script>

I´m using VS2012, ASP.NET with Razor.

The browser (Chome) says on console:

Uncaught TypeError: Cannot read property 'box1' of null

I have tried different approaches with no success.

[EDIT]

Working Code (had to forget d3 for a while):

<script type="text/javascript">

    var mySvg = document.getElementById("svgobject");
    alert(mySvg);
    mySvg.addEventListener("load", function () {
        var svg = mySvg.getSVGDocument();
        alert(svg);
        svg.getElementById("box1").setAttribute("fill", "green");
    });

</script>
4

1 回答 1

3

您可以省略 js 的前 2 行并简单地使用:

var item = d3.select("#box1")
item.style("fill", "blue");

或者,在一行中,正如拉斯建议的那样:

d3.select("#box1").style("fill", "blue");

由于您选择的是 SVG 元素,因此您必须使用该fill属性而不是color用于 html 的属性。

这是更新代码的小提琴。

于 2013-10-09T19:45:22.170 回答