Skip to content

Instantly share code, notes, and snippets.

@ge045
Forked from mbostock/.block
Last active March 27, 2016 13:24
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 ge045/06b2124acc52fa3c231f to your computer and use it in GitHub Desktop.
Save ge045/06b2124acc52fa3c231f to your computer and use it in GitHub Desktop.
d3.image test
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<!-- script src="/d3.js"></script -->
<script src="https://raw.githubusercontent.com/ge045/d3/feature/d3_image/d3.js"></script>
<script>
var width = 960, height = 500, fname = "readme.png";
//var width = 48, height = 64, fname = "small.jpg";
//var width = 480, height = 250, fname = "readme_xs.png";
var color = d3.scale.linear()
.domain([15, 35, 132])
.range(["#d7191c", "#ffffbf", "#2c7bb6"])
.interpolate(d3.interpolateHcl);
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height);
var context = canvas.node().getContext("2d");
var colorize = function(image)
{
return function(){
context.drawImage(image, 0, 0, width, height);
var imageData = context.getImageData(0, 0, width, height);
// Rescale the colors.
for (var c, i = 0, n = width * height * 4, d = imageData.data; i < n; i += 4) {
c = d3.rgb(color(d[i]));
d[i + 0] = c.r;
d[i + 1] = c.g;
d[i + 2] = c.b;
}
context.putImageData(imageData, 0, 0);
};
}
d3.image(fname, function(error, image) {
if (error!==null) return console.log(error);
canvas.attr("src", image.src)
image.onload = colorize(image);
}
);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment