Skip to content

Instantly share code, notes, and snippets.

@shimizu
Last active March 6, 2018 07:13
Show Gist options
  • Save shimizu/44ac0be6f0ce6e75bd62 to your computer and use it in GitHub Desktop.
Save shimizu/44ac0be6f0ce6e75bd62 to your computer and use it in GitHub Desktop.
SVG textで改行 part.1

古いバージョンのsafariなどで、動かないことがある。

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="//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("transform", "translate(100, 100)")
.html(leftLinebreak(textArray))
svg .append("text")
.attr("transform", "translate(100, 200)")
.html(rightLinebreak(textArray))
svg .append("text")
.attr("transform", "translate(100, 300)")
.html(centerLinebreak(textArray))
function leftLinebreak(array){
let string = "";
array.forEach((t, i) =>{
string += `<tspan y="${i}em" x="0em">${t}</tspan>`;
});
return string;
}
function rightLinebreak(array){
let string = "";
const maxTextLength = d3.max(array, d => d.length )
array.forEach((t, i) => {
let l = maxTextLength - t.length ;
string += `<tspan y="${i}em" x="${l}em">${t}</tspan>`;
});
return string;
}
function centerLinebreak(array){
let string = "";
const maxTextLength = d3.max(array, d => d.length )
array.forEach((t, i) => {
let l = (maxTextLength - t.length) /2;
string += `<tspan y="${i}em" x="${l}em">${t}</tspan>`;
});
return string
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment