Skip to content

Instantly share code, notes, and snippets.

@shimizu
Last active February 23, 2017 15:42
Show Gist options
  • Save shimizu/9a1fb770ed60c86abf5d1ee32a2098da to your computer and use it in GitHub Desktop.
Save shimizu/9a1fb770ed60c86abf5d1ee32a2098da to your computer and use it in GitHub Desktop.
SVG textで改行 part.3
license: mit
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment