Skip to content

Instantly share code, notes, and snippets.

@emeeks
Last active July 27, 2018 23:23
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 emeeks/11324978 to your computer and use it in GitHub Desktop.
Save emeeks/11324978 to your computer and use it in GitHub Desktop.
Canvas to dataURL to IMG Element

100 Circles are drawn with random colors using canvas, and each is stored as a dataURL and sent to an array. The array is then used to create a div with 100 image elements, each resized to 50px x 50px.

You'll need to click "open this in a new window" if you're viewing it on bl.ocks.org and want to see the small circles.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>D3 in Action Canvas Example 2</title>
<meta charset="utf-8" />
</head>
<script src="http://d3js.org/d3.v3.min.js" type="text/javascript"></script>
<script src="http://d3js.org/colorbrewer.v1.min.js"></script>
<style>
img {
width: 50px;
height: 50px;
float: left;
}
</style>
<body onload="canvasExample2()">
<div id="controls">
</div>
</body>
<footer>
<script>
function canvasExample2() {
imageArray = [];
d3.select("#controls").append("canvas").attr("height", 500).attr("width", 500);
var context = d3.select("canvas").node().getContext("2d");
context.textAlign = "center";
context.font="200px Georgia";
colorScale = d3.scale.quantize().domain([0,1]).range(colorbrewer.Reds[7]);
lineScale = d3.scale.quantize().domain([0,1]).range([10,40]);
for (var x=1;x<100;x++) {
context.clearRect(0,0,500,500);
context.strokeStyle = colorScale(Math.random());
context.lineWidth = lineScale(Math.random());
context.fillStyle = colorScale(Math.random());
context.beginPath();
context.arc(250,250,200,0,2*Math.PI);
context.fill();
context.stroke();
context.fillStyle = "black";
context.fillText(x,250,280);
var dataURL = d3.select("canvas").node().toDataURL();
imageArray.push(dataURL);
}
d3.select("#controls")
.append("div").attr("class", "gallery")
.selectAll("img").data(imageArray).enter().append("img")
.attr("src", function(d) {return d})
}
</script>
</footer>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment