Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've tried this different ways, but nothing seems to be working. Here is what I currently have:

var vis = d3.select("#chart").append("svg")
         .attr("width", 1000)
         .attr("height", 667),

 scaleX = d3.scale.linear()
        .domain([-30,30])
        .range([0,600]),

scaleY = d3.scale.linear()
        .domain([0,50])
        .range([500,0]),

poly = [{"x":0, "y":25},
        {"x":8.5,"y":23.4},
        {"x":13.0,"y":21.0},
        {"x":19.0,"y":15.5}];

vis.selectAll("polygon")
    .data(poly)
    .enter()
    .append("polygon")
    .attr("points",function(d) { 
        return [scaleX(d.x),scaleY(d.y)].join(",")})
    .attr("stroke","black")
    .attr("stroke-width",2);

I assume the problem here is either with the way I am defining the points data as an array of individual point objects, or something to do with how I'm writing the function for the .attr("points",...

I've been looking all over the web for a tutorial or example of how to draw a simple polygon, but I just can't seem to find it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
266 views
Welcome To Ask or Share your Answers For Others

1 Answer

A polygon looks something like: <polygon points="200,10 250,190 160,210" />

So, your full poly array should produce one long string that will create one polygon. Because we are talking about one polygon the data join should also be an array with only one element. That is why the code below shows: data([poly]) if you wanted two identical polygons you would change this to data([poly, poly]).

The goal is to create one string from your array with 4 objects. I used a map and another join for this:

poly = [{"x":0.0, "y":25.0},
        {"x":8.5,"y":23.4},
        {"x":13.0,"y":21.0},
        {"x":19.0,"y":15.5}];

vis.selectAll("polygon")
    .data([poly])
  .enter().append("polygon")
    .attr("points",function(d) { 
        return d.map(function(d) {
            return [scaleX(d.x),scaleY(d.y)].join(",");
        }).join(" ");
    })
    .attr("stroke","black")
    .attr("stroke-width",2);

See working fiddle: http://jsfiddle.net/4xXQT/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...