block by enjalot a2b28f0ed18b891f9fb70910f1b8886d

Quick, Draw! d3 & SVG demo

Full Screen

A simple example showing one way to render some Quick, Draw! data with d3.js & SVG.

The data was prepared using ndjson-cli as documented here.

Built with blockbuilder.org

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
  </style>
</head>

<body>
  <script>
    var width = 960;
    var height = 500;
    var blur = .8628;
    var svg = d3.select("body").append("svg")
      .attr("width", width)
      .attr("height", height)
    var g = svg.append("g") // for our zoom
        
    d3.json("canadian-faces.json", function(err, drawings) {
    // check the console to see the data format!
    console.log(drawings);

    var line =  d3.line()
      .x(function(d) { return d.x })
      .y(function(d) { return d.y })
      .curve(d3.curveBasis)

    var spacing = 90;
    var groups = g.selectAll("g.drawing").data(drawings)
    var groupsE = groups.enter().append("g")
    	.classed("drawing", true)
      .attr("transform", function(d,i) {
        // lay them out in a grid
        var x = -width + (i % 30) * spacing;
        var y = -height + Math.floor(i/30) * spacing
        return "translate(" + [x,y] + ")scale(0.25)" 
      })
    	// we style the groups instead of the individual paths for a slight performance boost
      .style("fill", "none")
      .style("stroke", "#111")
      .style("stroke-width", 9)
      .on("click", function(d) { console.log(d) })
//       .style("stroke-opacity", 0.5)
    var pathsE = groupsE.selectAll("path.stroke").data(function(d) { 
      // the data for each path is an array of points
      // but it doesn't start that way
      // the original format is [ [x0,x1,x2...], [y0,y1,y2...]]
      return d.drawing.map(function(s) {
        var points = []
        s[0].forEach(function(x,i) {
          points.push({x: x, y: s[1][i] })
        })
        return points;
      })
    }).enter().append("path").classed("stroke", true)
    
    pathsE
      .attr("d", line)
    
    var zoom = d3.zoom()
      .scaleExtent([1/12, 4])
      .on("zoom", function() {
        g.attr("transform", d3.event.transform)
      })
    svg.call(zoom)
  })
    
  var defs = svg.append("defs");
  var filter = defs.append("filter").attr("id","gooeyCodeFilter");
  filter.append("feGaussianBlur")
    .attr("in","SourceGraphic")
    .attr("stdDeviation",blur)
    .attr("color-interpolation-filters","sRGB")
    .attr("result","blur");
  filter.append("feColorMatrix")
    .attr("in","blur")
    .attr("mode","matrix")
    .attr("values","1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 18 -7")
    .attr("result","gooey")
  g.style("filter", "url(#gooeyCodeFilter)")

  </script>
</body>