Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active September 19, 2018 00:54
Show Gist options
  • Select an option

  • Save codetricity/ed072ff40e11ee3cd6c3cadb47476ad7 to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/ed072ff40e11ee3cd6c3cadb47476ad7 to your computer and use it in GitHub Desktop.
create SVG Viewport

Temperature by Month 4 - svg viewport

Learning Objectives

  • use keyword const instead of variable if the variable for WIDTH and HEIGHT do not change
  • use ALL_CAPS convention for the const name wich as WIDTH
  • review SVG Viewport margin conventions
  • review chart area position translation to get X and Y axis aligned properly

Steps

  1. create constants for WIDTH and HEIGHT of chart area 800x600

  2. create const MARGIN as a JavaScript object with properties LEFT, RIGHT, TOP, BOTTOM

  3. create variables for SVG_WIDTH and SVG_HEIGHT by adding chart areas to margins

  4. use d3.select to select the HTML body element

  5. append svg

  6. add attributes for width and height to the new svg element

    svg viewport

  7. append group g to the svg HTML tag

          .append("g")
    
  8. translate g by MARGIN.LEFT and MARGIN.TOP

         .attr("transform", "translate(" + 
         ...
    

Example

  const WIDTH = 800;
  const HEIGHT = 600;

  const MARGIN = {TOP: 50, BOTTOM: 100, RIGHT: 50, LEFT: 100};
  const SVG_HEIGHT = HEIGHT + MARGIN.TOP + MARGIN.BOTTOM;
  const SVG_WIDTH = WIDTH + MARGIN.RIGHT + MARGIN.LEFT;

  var svg = d3.select("body").append("svg")
      .attr("width", SVG_WIDTH)
      .attr("height", SVG_HEIGHT)
          .append("g")
              .attr("transform", "translate(" + 
                  MARGIN.LEFT + "," + MARGIN.TOP + ")");

Exercises

Use CodePen for exercises

codepen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment