Can you make a sentence appear with each individual letter rotating and getting larger?
This is my approach:
I decided to split the sentence into separate span
elements, one for each letter. Then I used CSS transform -webkit-transform
to animate the letters. Unfortunately, this didn't work in Chrome until I added display: inline-block
. However, this caused the spaces between words to disappear, making everything run together.
Check out the example below or here
let containerDiv = "div.chart";
function displayText(_textArray) {
let sel = d3.select(containerDiv);
// add headers for all strings but the last one
for (let i = 0; i < _textArray.length - 1; i++) {
sel.append("div")
.attr("class", "header h" + i)
.append("h1")
.attr("class", "trans")
.text(_textArray[i]);
}
// add last string by wrapping each letter around a span
// which can be styled individually
let sel2 = sel.append("div")
.attr("class", "header h" + (_textArray.length - 1))
.append("h1")
.style("opacity", 1)
.attr("class", "trans");
const lastString = _textArray[_textArray.length-1];
for (let i = 0; i < lastString.length; i++) {
sel2.append("span")
.attr("class", "color-" + (i % 5))
.text(lastString[i]);
}
}
function transitionLetters(_selection){
_selection
.transition()
.duration(2000)
.delay((d,i) => i * 200)
.style("opacity", 1)
.style("-webkit-transform", "rotate(-720deg) scale(1)");
}
let myText = ["I like to eat", "ham and eggs"];
displayText(myText);
d3.selectAll("span").call(transitionLetters);
div.header {
margin: 0 auto;
text-align: center;
width: max-content;
}
h1 span {
opacity: 0;
display: inline-block;
-webkit-transform: rotate(-0deg) scale(0.001);
}
.color-0 { color: rgb(255, 0, 171); }
.color-1 { color: rgb(0, 168, 255); }
.color-2 { color: rgb(171, 0, 255); }
.color-3 { color: rgb(255, 171, 0); }
.color-4 { color: rgb(168, 255, 0); }
<script src="https://d3js.org/d3.v4.min.js"></script>
<meta charset="utf-8">
<body>
<div class="chart"></div>
</body>