はじめに
* SVGオブジェクト配下にテキストを表示をする場合、\n や <br> は、改行されない。 * 考える際に以下のサイトが役に立った。感謝。http://qiita.com/hnakamur/items/cfb8b0005488a2f34fb0
以下も今後のために見ておきたい
http://plnkr.co/edit/YBCAc3?p=preview
http://bl.ocks.org/mbostock/7555321
方法
* SVGで複数行のテキストを扱うには、以下の3つのいずれか。 [1] 行ごとにtext要素を作成 => 要するに、行ごとに配列をもち、それぞれ出した位置に描画。(以下のサイトを参照)http://webbeginner.hatenablog.com/entry/2014/07/18/140745
サンプル
http://jsdo.it/jnobuyuki/3YIz
=> ただこのやり方だと、データの持ち方が限定される。 [2] 1つのtext内に行ごとにtspan要素を作成 => こちらを選択。 [3] foreignObjectを使ってHTMLを埋め込む => ブラウザでできない可能性があるとのこと。 ほかにも「.html("test" + "<br/>" + "test")」などもあるって書いてあったが実現できなかったhttp://stackoverflow.com/questions/13049050/can-you-insert-a-line-break-in-text-when-using-d3-js
サンプル
http://qiita.com/hnakamur/items/cfb8b0005488a2f34fb0の方法を「改行入れのテキストを表示する」にフォーカスさせただけだが
<html> <body> <script src="">http://d3js.org/d3.v3.js"> <script> var graphAreaWidth = 500; var graphAreaHeight = 300; var lineHeight = 1.4; var svg = d3.select("body") .append("svg") .attr({width: graphAreaWidth, height: graphAreaHeight}) .append('g'); svg.append("text") .attr("transform", function(d) { return "translate(" + graphAreaWidth / 2 + "," + graphAreaHeight / 2 + ")"; }) .text("1234567890<br>1234567890<br>1234567890<br>01234567890") .call(convertNewline, lineHeight); function convertNewline(texts, lineHeight) { texts.each(function() { var text = d3.select(this), lines = text.text().split(/<br>/), lineCount = lines.length, i, line, y; text.text(''); for (i = 0; i < lineCount; i++) { line = lines[i]; y = (i - (lineCount - 1) / 2) * lineHeight; text.append('tspan') .attr({ 'x': 0, 'y': y ? y + 'em' : 0, 'dy': '.35em' }) .text(line); } }); } </script> </body> </html>
出力結果
1234567890 1234567890 1234567890 01234567890