block by emeeks 11324978

Canvas to dataURL to IMG Element

Full Screen

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.

index.html

<html xmlns="//www.w3.org/1999/xhtml">
<head>
  <title>D3 in Action Canvas Example 2</title>
  <meta charset="utf-8" />
</head>
<script src="//d3js.org/d3.v3.min.js" type="text/javascript"></script>
<script src="//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>