Skip to content

Instantly share code, notes, and snippets.

@cjhin
Last active October 3, 2016 02:31
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 cjhin/9bfbaa34db720c6c5a891b822e68fab4 to your computer and use it in GitHub Desktop.
Save cjhin/9bfbaa34db720c6c5a891b822e68fab4 to your computer and use it in GitHub Desktop.
Triforce
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.triangle-gold {
fill: gold;
}
.triangle-flashing {
fill: white;
transition: fill 1.5s ease;
}
.active {
fill: forestgreen;
}
</style>
<body>
<svg id='main' width=960 height=500></svg>
</body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
/* Playing with d3.symbol, specifically triangles */
var triangleSize = 1000;
var triangleWidth = 48.06;
var triangleHeight = 41.62;
var width = d3.select('#main').attr("width");
var height = d3.select('#main').attr("height");
var triangles = [];
var N = 12;
for(var i = -1.0*N; i < N; i ++) {
for(var j = -1.0*N; j < N; j ++) {
var oddOffset = j % 2 - 1;
triangles.push({ x: i + (oddOffset*0.5), y: j*1 });
}
}
var triangle = d3.symbol()
.type(d3.symbolTriangle)
.size(triangleSize);
d3.select('#main')
.selectAll(".triangle")
.data(triangles)
.enter().append("path")
.attr("d", triangle)
.attr("class", function(d) {
var classString = "triangle";
// only color the middle three gold
if(d.x == 0.5 && d.y == 0 || d.x == 0 && d.y == 1 || d.x == 1 && d.y == 1) {
classString += " triangle-gold";
} else {
classString += " triangle-flashing";
}
return classString;
})
.attr("transform", function(d) {
var newX = (width / 2.0) + (triangleWidth * d.x);
var newY = (height / 2.0) + (triangleHeight * d.y);
return "translate(" + newX + "," + newY + ")";
});
function animate() {
d3.selectAll(".triangle-flashing").each(function(t) {
var dice = Math.random();
// effectively a 90% chance to "fade out" an existing triangle
// and a 99% chance to "fade in" a new triangle
// the code would look more clear as two if statements but I wanted to optimize
// the relatively expensive call to d3.select(this);
if(dice > 0.9) {
var currTriangle = d3.select(this);
if(currTriangle.attr("class").indexOf("active") > 0) {
currTriangle.classed("active", false);
} else if(dice > 0.99) {
currTriangle.classed("active", true);
}
}
});
}
setInterval(animate, 1500);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment