Skip to content

Instantly share code, notes, and snippets.

@anbnyc
Last active November 18, 2016 15:34
Show Gist options
  • Save anbnyc/0121e8c412ebb173a4b9859c51c22ee2 to your computer and use it in GitHub Desktop.
Save anbnyc/0121e8c412ebb173a4b9859c51c22ee2 to your computer and use it in GitHub Desktop.
Interval + Gradient Progress Bar
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.js"></script>
<style>
body{
padding: 12px;
}
text{
font: Garamond;
font-size: 12px;
}
rect.inner-progress{
fill: white;
stroke-width: 1px;
stroke-opacity: 1;
stroke: black;
}
rect.progress{
stroke: black;
stroke-width: 1px;
}
</style>
</head>
<body>
<svg>
<g>
<rect class="progress"></rect>
<rect class="inner-progress"></rect>
<text></text>
</g>
</svg>
<script>
var width = 400;
var height = 36;
var pct = .75;
var svg = d3.select("svg")
.attr("width",width+100);
var gradient = svg
.append("defs")
.append("linearGradient")
.attr("id","gradient")
.attr("x1","0%")
.attr("y1","50%")
.attr("x2","100%")
.attr("y2","50%");
gradient.append("stop")
.attr("offset","0%")
.attr("stop-color","#f00")
.attr("stop-opacity",1);
gradient.append("stop")
.attr("offset","100%")
.attr("stop-color","#080")
.attr("stop-opacity",1);
d3.select(".progress")
.attr("height",height)
.attr("width",width)
.attr("fill","url(#gradient)");
d3.select(".inner-progress")
.attr("height",height)
.attr("x",pct*width)
.attr("width",(1-pct)*width);
d3.select("text")
.attr("transform","translate(5,22)")
.attr("x",pct*width)
.text(cleanUp(pct));
function cleanUp(val){
return Math.round(val*100)+"%";
}
var t = d3.transition()
.duration(500);
d3.interval(function(){
pct = Math.random();
d3.select(".inner-progress")
.attr("height",height)
.transition(t)
.attr("x",pct*width)
.attr("width",(1-pct)*width);
d3.select("text")
.text(cleanUp(pct))
.transition(t)
.attr("x",pct*width);
},2000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment