2013-10-09 84 views
0

我想使用d3更改SVG somen元素屬性。實際上,我將通過AJAX從服務器數據下載,這些數據將根據數據值更改SVG元素的顏色。使用d3更改SVG元素

這是我的一段代碼來改變SVG元素圖形行爲:

SVG示例文件:

<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代碼:使用VS2012,ASP

<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。 NET與剃刀。

瀏覽器(丁目)說,在控制檯上:

遺漏的類型錯誤:無法讀取空

我曾嘗試沒有成功不同方法的特性「盒1」。

[編輯]

工作守則(不得不丟開D3):

<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> 
+0

你試過'd3.select( 「矩形」)的風格( 「補」, 「藍」);'? –

回答

2

您可以省略前兩行的JS和簡單的使用:

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

或者,在一行中,如Lars所示:

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

由於您選擇的是SVG元素,因此您必須使用fill屬性,而不是用於html的color

Here is the fiddle with the update code.

+0

在我的環境中完全不能工作:VS2012,ASP.NET,MVC4,Razor。我有一個添加菜單和內容包裝的_Layout文件。奇怪。現在在Chrome控制檯上沒有任何錯誤... – Mendes

+0

也許還有別的東西會導致問題?你的AJAX請求是否返回任何內容? –

+0

我在VS中創建了一個空白項目,並添加了這個代碼。 Chome顯示沒有錯誤,但不會改變顏色。在IE上,不改變顏色,我得到了這樣的消息:在http:// localhost:7408/Scripts/d3-master/d3.js第24行第5列未處理的異常 0x800a138f - 無法獲取'prototype'屬性值:該對象爲空或未驗證(翻譯)。 – Mendes