D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
shimizu
Full window
Github gist
SVG textで改行 part.3
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <title>SVG textで改行</title> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } svg { width: 100%; height: 100%; } </style> </head> <body> <svg></svg> <script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script> <script> !(function(){ "use strict" var textArray = ["1行目、あ","2行目", "3行目あああああ", "4行目あ"] var svg = d3.select("svg"); svg .append("text") .datum(textArray) .attr("transform", "translate(100, 100)") .each(leftLinebreak) svg .append("text") .datum(textArray) .attr("transform", "translate(100, 200)") .each(rightLinebreak) svg .append("text") .datum(textArray) .attr("transform", "translate(100, 300)") .each(centerLinebreak) function leftLinebreak(array){ d3.select(this).selectAll("tspan") .data(array) .enter() .append("tspan") .attr("x", "0em") .attr("y", function(d,i){ return i + "em"}) .text(function(d){ return d }) } function rightLinebreak(array){ var maxTextLength = d3.max(array, function(d){ return d.length }) d3.select(this).selectAll("tspan") .data(array) .enter() .append("tspan") .attr("x", function(d,i){ var l = maxTextLength - d.length ; return l + "em" }) .attr("y", function(d,i){ return i + "em"}) .text(function(d){ return d }) } function centerLinebreak(array){ var maxTextLength = d3.max(array, function(d){ return d.length }) d3.select(this).selectAll("tspan") .data(array) .enter() .append("tspan") .attr("x", function(d,i){ var l = (maxTextLength - d.length) /2 return l + "em" }) .attr("y", function(d,i){ return i + "em"}) .text(function(d){ return d }) } }()); </script> </body>
https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js