Skip to content

Instantly share code, notes, and snippets.

@ja-k-e
Last active August 29, 2015 14:21
Show Gist options
  • Save ja-k-e/ddfde65bb9bc8a5fa0d2 to your computer and use it in GitHub Desktop.
Save ja-k-e/ddfde65bb9bc8a5fa0d2 to your computer and use it in GitHub Desktop.
Random SVG Polygons Splotch Animation

Random SVG Polygons Splotch Animation

Randomly generated SVG polygons with CSS opacity animations.

Should have called this "BattDrain MemHog 5000"

A Pen by Jake Albaugh on CodePen.

License.

var w = window.innerWidth, h = window.innerHeight,
radius_ratio = 1,
radius_x = w * radius_ratio, radius_y = h * radius_ratio,
fill = "rgba(0,0,0,0.03)",
min_polygon = 3, max_polygon = 6,
polygons = 200;
function randomXY(plot_area) {
var x = (Math.random() * (plot_area.max_x - plot_area.min_x)) + plot_area.min_x,
y = (Math.random() * (plot_area.max_y - plot_area.min_y)) + plot_area.min_y;
return x + "," + y + " ";
}
function randomPolygon() {
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"),
svgNS = svg.namespaceURI;
// svg attributes
svg.setAttribute("id", "svg");
svg.setAttribute("width", w);
svg.setAttribute("height", h);
// polygon loop
for(var p = 0; p < polygons; p ++) {
// create the polygon
var polygon = document.createElementNS(svgNS, "polygon"),
// random center for the polygon
center_x = Math.random() * w,
center_y = Math.random() * h,
plot_area = {
min_x: (center_x - radius_x < 0) ? 0 : center_x - radius_x,
max_x: (center_x + radius_x > w) ? w : center_x + radius_x,
min_y: (center_y - radius_y < 0) ? 0 : center_y - radius_y,
max_y: (center_y + radius_y > h) ? h : center_y + radius_y
},
// polygon points must be between min and max points
point_count = Math.round(Math.random() * (max_polygon - min_polygon)) + min_polygon,
points = "";
// generate points
for(var i = 0; i < point_count; i++) { points += randomXY(plot_area); }
// apply points
polygon.setAttribute("points", points);
// style polygon fill and stroke
polygon.setAttribute("fill", fill);
polygon.setAttribute("stroke", "none");
// append polygon to svg
svg.appendChild(polygon);
}
// append svg to body
document.body.appendChild(svg);
}
randomPolygon();
$polygon-count: 200;
body { background: #CCC; }
#svg {
position: absolute;
left: 50%; top: 50%;
transform: translate3d(-50%,-50%, 0);
}
#svg polygon {
opacity: 0;
animation: polygon 2s linear infinite;
@for $i from 1 through $polygon-count {
&:nth-child(#{$i}) { animation-delay: 10ms * $i; }
}
}
@keyframes polygon {
0%, 100% { opacity: 0; }
50% { opacity: 1; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment