Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - Proper format for drawing polygon data in D3

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

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

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...