Last active
July 24, 2019 06:56
-
-
Save nategood/183376b985947fecf2dc to your computer and use it in GitHub Desktop.
Image Data to SVG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<style> | |
html, body { | |
margin: 0; padding: 0; | |
} | |
circle { | |
stroke-width: 0; | |
fill-opacity: 0.5; | |
} | |
svg { | |
margin: auto; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="viewport" style="display:none"></canvas> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script> | |
var url = "nate.png"; | |
var windowW = 960, windowH = 500; | |
var w = 299, h = 368; | |
var ratio = w / h; | |
var samples = 5000; | |
var maxRadius = 7, minRadius = 2; | |
var canvas = document.getElementById("viewport"); | |
var context = canvas.getContext("2d"); | |
var scale = d3.scale.linear() | |
.domain([w, h]) | |
.range([windowH * ratio, windowH]); | |
canvas.width = w; | |
canvas.height = h; | |
img = new Image(); | |
img.src = url; | |
img.onload = function() { | |
context.drawImage(img, 0, 0); | |
// returns array with length pixels * 4, each pixel has r g b and a | |
var data = context.getImageData(0, 0, w, h).data; | |
var points = []; | |
for (var s = 0; s < samples; s++) { | |
var i = Math.floor(Math.random() * w * h) * 4; | |
var p = Math.floor(i / 4); // pixel index | |
var x = p % w, | |
y = Math.floor(p / w), | |
c = d3.rgb(data[i], data[i+1], data[i+2]).toString(); | |
if (c === "#ffffff") continue; | |
points.push([scale(x), scale(y), c]); | |
} | |
var offset = (windowW / 2 - scale(w) / 2); | |
var svg = d3.select("body").append("svg") | |
.style("background", "#fff") | |
.attr("width", windowW) | |
.attr("height", windowH) | |
.append("g") | |
.attr("transform", "translate(" + offset + " 0)"); | |
svg.selectAll("circle") | |
.data(points) | |
.enter().append("circle") | |
.style("fill", function(d) { return d[2]; }) | |
.attr("r", function() { return (maxRadius - minRadius) * Math.random() + minRadius; }) | |
.attr("transform", function(d) { return "translate(" + (Math.random() * windowW - offset) + " " + (Math.random() * windowH) + ")"; }) | |
.transition() | |
.delay(500) | |
.ease("elastic") | |
.duration(1000) | |
.attr("transform", function(d) { return "translate(" + d[0] + " " + d[1] + ")"; }); | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment