A function to make "tick" text if it's too long for its containter (or clip-path)
Built with blockbuilder.org
license: mit |
A function to make "tick" text if it's too long for its containter (or clip-path)
Built with blockbuilder.org
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<head> | |
<link href='https://fonts.googleapis.com/css?family=Play' rel='stylesheet' type='text/css'> | |
<style> | |
body { | |
margin:auto; | |
font-family: 'Play', sans-serif; | |
font-size:100%; | |
} | |
text { | |
font-family: 'Play', sans-serif; | |
} | |
</style> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script src="ticker.js"></script> | |
<body> | |
</body> | |
<script> | |
ticker(); | |
</script> |
function ticker(width,height,margin) { | |
width = width || 960; | |
height = height || 500; | |
margin = margin || {top:20, left:50, bottom:50, right:20}; | |
width = width - margin.left - margin.right; | |
height = height - margin.top - margin.bottom; | |
var svg = d3.select('body') | |
.append("svg") | |
.attr("height", height + margin.top + margin.bottom) | |
.attr("width", width + margin.left + margin.right) | |
.attr("viewBox","0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom)) | |
.style("-webkit-user-select","none") | |
.style("cursor","default") | |
.append("g") | |
.attr("transform","translate(" + margin.left + "," + margin.top + ")"); | |
var tickerText = 'This text is much too long to fit in the rectangle...' | |
var g = svg.append("g") | |
.attr("transform","translate(100,100)"); | |
var rect = g.append("rect") | |
.attr("width",400) | |
.attr("height",100) | |
.style("fill","#b5cde1"); | |
g.append("clipPath") | |
.attr("id","cp") | |
.append("rect") | |
.attr("width",400) | |
.attr("height",100); | |
var text = g.append("text") | |
.attr("clip-path","url(#cp)") | |
.text(tickerText) | |
.style("fill","black") | |
.attr("y","1em") | |
.style("font-size", "6em") | |
tickText(text,400,10000); | |
function tickText(textSelection, maxWidth,duration) { | |
if(textSelection.node().getBBox().width > maxWidth) { | |
var w = textSelection.node().getBBox().width; | |
var x0 = +textSelection.attr("x") || 0; | |
textSelection.attr("x",x0); | |
function tick() { | |
textSelection | |
.transition() | |
.ease(d3.easeLinear) | |
.duration(duration) | |
.attr("x",-w) | |
.transition() | |
.duration(0) | |
.attr("x",maxWidth) | |
.on("end",tick) | |
} | |
tick(); | |
} | |
} | |
} |