Dynamic HTML &SVG With D3

I tried once to include an SVG element inside an HTML5 page, and add path elements dynamically as a response to mouse events. Doing it with Vanilla JS is not a good idea because

  • Coordinates in SVG are relative to the SVG elements, while mouse coordinates are relative to the page.
    Translating the coordinates using ‘getBoundingClientRect’ works fine in Firefox, but not in Explorer 9 after scrolling.
    D3 offers the function d3.mouse(container) that translte the mouse coordinates to coordinates relative to the container. For example:

    var coords = d3.mouse(svgElement.node());

  • SVG sub-elements, such as paths cannot be created using ‘document.createElement’.
    In Vanillas JS, you should create them with "document.createElementNS(‘http://www.w3.org/2000/svg’, ‘path’)
    In D3, you simply type “svgElement.append(‘path’)”.

If you wonder what “svgElement” is, It is a selection object, created using “d3.select(‘svg’)”, which returns the first (and only) SVG element on the HTML page.

  • D3 allows you to create SVG shapes that can be added as the “d”(path data) attribute of paths. For example:

    .attr(“d”, line);
    (when “line” is a line shape created by ‘d3.svg.line’). Read more about SVG shapes here.

D3 can be downloaded from this page.
In addition, you can find a good API reference here.

So basiclly this is a wrapper for the times one wants to have mouse events dynamically change the SVG code?

It is a Javascript framework that includes classes that make handling SVG elements easier. ‘d3.mouse’ returns coordinates of the event translated.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.