Tuesday, October 21, 2014

SVG canvas in d3.js


D3 need to be able to have a space defined for it to draw things. And when you define the space it's going to use, you can also give the space you're going to use a name, attributes and positions within that space a designation.



Example:
          var svg = d3.select("body")
               .append("svg")
                     .attr("width", width + margin.left + margin.right)
                      .attr("height", height + margin.top + margin.bottom)
               .append("g")
                      .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

In the above example 'append' is used to add the svg element (a canvas that we are going to draw things on) to the body element.

We also add an element 'g' that is referenced to the top left corner of the actual graph area on the canvas. 'g' is actually a grouping element in the sense that it is normally used for grouping together several related elements. So in this case those grouped elements will have a common reference.

In the above example we also added g element, the element is referenced to the top left corner of the graph area. Here 'g' is a grouping element I already mentioned in 'SVG Group Elements'  blog.



append("svg")
    .attr("width", width + margin.left + margin.right)
     .attr("height", height + margin.top + margin.bottom)



The above code tells us that the 'svg' element has a "width" of width + margin.left + margin.right and the "height" of height + margin.top + margin.bottom.


  .append("g")
       .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

The above code tells us that the element "g" has been transformed by moving(translating) to the point margin.left, margin.top.This way when we tell something to be drawn on our canvas, we can use the reference point "g" to make sure everything is in the right place.

No comments:

Post a Comment