Skip to content

Instantly share code, notes, and snippets.

@HashNuke
Created October 29, 2015 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HashNuke/90c00fd9ae08fdf269dc to your computer and use it in GitHub Desktop.
Save HashNuke/90c00fd9ae08fdf269dc to your computer and use it in GitHub Desktop.
Buildings and the moon OR a bar chart
<!doctype html>
<html>
<head>
<title>Buildings and the moon OR a bar chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
</head>
<body>
<svg>
<defs>
<linearGradient id="night-sky" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="10%" style="stop-color:#000; stop-opacity:1"></stop>
<stop offset="100%" style="stop-color:#CC6699; stop-opacity:1"></stop>
</linearGradient>
<linearGradient id="moon" x1="0%" y1="30%" x2="50%" y2="100%">
<stop offset="30%" style="stop-color:#111; stop-opacity:1"></stop>
<stop offset="100%" style="stop-color:#ccc; stop-opacity:1"></stop>
</linearGradient>
</defs>
</svg>
<script>
window.onload = function() {
var data = [];
var width = 480,
height = 320;
var bgHeight = 220;
var barWidth = 30;
var baseHeight = 40;
var heightLimit = 140;
var roadWidth = height - bgHeight;
for(var i=0; i < 20; i++) {
var randomN = Math.floor(Math.random() * (heightLimit - baseHeight));
data.push(randomN + baseHeight);
}
var svg = d3.select("svg")
.attr("height", height)
.attr("width", width);
svg.append("rect")
.attr({x: "0", y: "0"})
.attr({width: width, height: bgHeight})
.attr("fill", "url(#night-sky)");
svg.append("circle")
.attr({cx: 400, cy: 30, r: 20})
.attr('fill', 'url(#moon)')
.attr('opacity', '0.95');
svg.append("circle")
.attr({cx: 400, cy: 30, r: 20})
.attr('fill', 'url(#moon)')
.attr('opacity', '0.95');
svg.selectAll(".building")
.data(data).enter()
.append("rect")
.attr("class", "building")
.attr("x", function(d, i){
return i * barWidth;
})
.attr("y", function(d){
return bgHeight - d;
})
.attr("width", function(d) {
// widen some buildings
if ((d/heightLimit)*100 > 80)
return barWidth + (barWidth/2);
else if ((d/heightLimit)*100 > 70)
return barWidth + (barWidth/4);
else
return barWidth;
})
.attr("height", function(d) {
return d;
})
.attr("fill", function() {
return ["#000", "#191919", "#121212"][Math.floor(Math.random() * 3)];
});
svg.append("rect")
.attr("x", 0)
.attr("y", bgHeight)
.attr("width", width)
.attr("height", roadWidth)
.attr("fill", "#00f");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment