Created
March 22, 2013 23:11
-
-
Save Valodim/5225460 to your computer and use it in GitHub Desktop.
rendering a moodbar .mood file as an svg with d3 in javascript
This file contains hidden or 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
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script> | |
// takes .mood files from moodbar as input | |
var files = [ | |
"05 - Awolnation - Jump On My Shoulders.mood" | |
]; | |
files.forEach(function(f) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', f, true); | |
// Hack to pass bytes through unprocessed. | |
xhr.overrideMimeType('text/plain; charset=x-user-defined'); | |
xhr.onreadystatechange = function(e) { | |
if (this.readyState == 4 && this.status == 200) { | |
var rgb = new Array(this.responseText.length / 3); | |
for (var i = 0, len = rgb.length; i < len; i++) { | |
var r = this.responseText.charCodeAt(i*3+0) & 0xff; | |
var g = this.responseText.charCodeAt(i*3+1) & 0xff; | |
var b = this.responseText.charCodeAt(i*3+2) & 0xff; | |
rgb[i] = { | |
offset: (i / len * 100) + "%", | |
color: "rgb(" + r + ", " + g + ", " + b + ")" | |
}; | |
} | |
var div = d3.select("body").append("div"); | |
div.append("div").text(f); | |
var svg = div.append("svg") | |
.attr("height", 20) | |
.append("g"); | |
svg.append("linearGradient") | |
.attr("id", "moodbar-gradient-" + f[0] + f[1]) | |
.attr("gradientUnits", "userSpaceOnUse") | |
.selectAll("stop") | |
.data(rgb) | |
.enter().append("stop") | |
.attr("offset", function(d) { return d.offset; }) | |
.attr("stop-color", function(d) { return d.color; }); | |
svg.append("rect") | |
.attr("fill", "url(#moodbar-gradient-" + f[0] + f[1] + ")") | |
.attr("x", 0) | |
.attr("y", 0) | |
.attr("width", "100%") | |
.attr("height", "10") | |
} | |
}; | |
xhr.send(); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are da real mvp !