D3.jsでは複数の図形を操作するにはselectAll()メソッドを使います。
selectAll()メソッドの引数には要素名、CSSクラス名を指定します。
該当する要素があれば、それらすべてを戻り値として返します。
メソッドチェーン利用時は、該当する要素すべてに対して処理が
行われます。
前回の記事で、特定のCSSクラス名を持つrect要素のスタイルを変更
しましたが、select()メソッドで変更できるのは最初に該当したもの
だけでした。selectAll()を使えば該当するCSSクラス名をもつ
rect要素のスタイルが全て変更できます。
selectAll()メソッドを使った場合、複数の要素が返されますが、
スタイルなどを設定するために繰り返し処理を書かなくて良いです。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>classを付しスタイルを摘要する</title> <script src="../js/d3.js"></script> <style> svg{ width:320px; height:240px; border:2px solid black; } rect{fill:green;} .pink{fill:pink;} </style> </head> <body> <h2>attr()メソッドでclassを付しスタイルを摘要する</h2> <svg> <rect x="120" y="20" width="20" height="20" class="rect2" /> <rect x="120" y="45" width="20" height="20" class="rect2" /> <rect x="120" y="70" width="20" height="20" class="rect2" /> <rect x="120" y="95" width="20" height="20" class="rect2" /> </svg> <script src="test.js"></script> </body> </html> |
1 2 3 4 5 6 7 |
d3.selectAll(".rect2") .attr("class","pink"); d3.selectAll(".pink") //CSSクラス名pinkを指定 .style("stroke","green") //枠の色を緑 .style("stroke-width","4px");//枠の幅4px |
特定の要素を操作する
select()メソッドは1つの要素を、selectAll()メソッドは複数の要素を
操作できます。じゃあ、特定の位置(4番目や7番目等)にあるrect要素を
操作するには・・・結論をいうと、
d3.jsでは、attr()メソッドやstyle()メソッドの第2引数に関数を
指定することで、繰り返し処理に介入できます。関数は要素を
1つ処理するたびに呼び出されます。for文やeach()メソッドで1つずつ
処理するのと同様の事ができます。
実際にやってみます。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>特定の場所にあるrect要素のスタイルを変更する</title> <script src="../js/d3.js"></script> <style> svg{ width:320px; height:240px; border:2px solid black; } rect{fill:green;} .pink{fill:pink;} </style> </head> <body> <h2>任意のrect要素のスタイルを変更する</h2> <svg> <rect x="120" y="20" width="20" height="20" class="rect2" /> <rect x="120" y="45" width="20" height="20" class="rect2" /> <rect x="120" y="70" width="20" height="20" class="rect2" /> <rect x="120" y="95" width="20" height="20" class="rect2" /> </svg> <script src="test.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 |
d3.selectAll("rect") //全てのrect要素を指定する .style("fill",function(d,i){ /* style()の2番目の引数で関数を指定 */ /* 出現の順番を調べ、0番目と2番目なら rect要素のfill:redを返す */ if( i % 2 == 0 ) return "red"; }); |