Search code examples
javascriptpathd3.jsarea

Why isn't this d3 hexagon drawing correctly?


I have made a code to make a simple hexagon but for some reason it is not drawing correctly. I am using "A", xDiff and yDiff as variables so I can change the size and location of the hexagon on the fly but it has a weird "tail". Is one of my points wrong? Oh, and _s32 is the square root of 3 divided by two.

        var _s32 = (Math.sqrt(3)/2);
        var A = 25;
        var xDiff = 100;
        var yDiff = 1000;
        var pointData = [[A+xDiff, 0+yDiff], [A/2+xDiff, A*_s32+yDiff], [-A/2+xDiff, A*_s32+yDiff], [-A+xDiff, 0+yDiff],
        [-A/2+xDiff, -A*_s32+yDiff], [A/2+xDiff, -A*_s32+yDiff]];
        var svgContainer = d3.select("body") //create container
                .append("svg")
                .attr("width", 1000)
                .attr("height", 1000);

        var enterElements = svgContainer.selectAll("path.area") //draw elements
                .data([pointData]).enter().append("path")
                .style("fill", "#ff0000")
                .attr("d", d3.svg.area());

Solution

  • First, yDiff being at 1000 positions your hexagon nearly outside of your SVG, so you should change it to, like, 100.

    Next, you're using d3.svg.area(), which is built to do more than just draw a path corresponding to the points you pass into it; rather, it's actually trying to add points in order to draw what would normally be the area under the graph, which in your case is meaningless. Instead, just use the d3.svg.line() function, which will just do what you need without trying to add any other points.

    Here's a jsFiddle: http://jsfiddle.net/LJuRp/