block by shimizu 67e6550f51b510d0e1ee

SVG textで改行 part.2

Full Screen

古いブラウザでも動くが、x座標をtranslateで調整しているのであまりスマートではない。

Built with blockbuilder.org

index.html

<!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="//unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>  
<script src="//unpkg.com/d3@4.12.2/build/d3.min.js"></script>    
<script type="text/babel">
const  textArray = ["1行目、あ","2行目", "3行目あああああ", "4行目あ"];
  
const svg = d3.select("svg");
  
  svg .append("text")
    .attr("text-anchor","start")
    .attr("transform", "translate(100, 100)")    
    .selectAll("tspan")
    .data(textArray)
    .enter()
    .append("tspan")
    .attr("y", (d,i) => `${i + i*0.2}em`)
    .attr("x", "0em")
    .text(d => d );

  svg .append("text")
    .attr("text-anchor","end")
    .attr("transform", "translate(230, 200)")    
    .selectAll("tspan")
    .data(textArray)
    .enter()
    .append("tspan")
    .attr("y", (d,i) => `${i + i*0.2}em`)
    .attr("x", "0em")
    .text(d => d);
  
    svg .append("text")
    .attr("text-anchor","middle")
    .attr("transform", "translate(160, 300)")    
    .selectAll("tspan")
    .data(textArray)
    .enter()
    .append("tspan")
    .attr("y", (d,i) => `${i + i*0.2}em`)
    .attr("x", "0em")
    .text(d => d);
  
</script>
</body>