简体   繁体   中英

drawing SVG polylines in a loop using javascript

I am fairly new to HTML and javascript and I am trying t adjust a piece of code I found online.

I created a json file which I read as data. In it are links which used to have an x1, x2, y1 and, y2 coordinate (straight lines). I used the following piece of code to create SVG line elements.

var link = svg
    .selectAll("line")
    .data(data.links)
    .enter()
    .append("line")
    .attr("x1", d => (d.x1 + translatex) * scale)
    .attr("x2", d => (d.x2 + translatex) * scale)
    .attr("y1", d => (d.y1 + translatey) * scale)
    .attr("y2", d => (d.y2 + translatey) * scale)
    .attr("id", d => (d.id))
    .attr("stroke", "black")

This worked fine. However since I am now running into situations where the lines are no longer straight per se I want to adjust this piece of code to draw polylines. So instead of the links having x1, y1 etc it now has a list of points. (which may vary in length)

I am struggling how to draw this using javascript. I tried the following:

var link = svg
    .selectAll("polyline")
    .data(data.links)
    .enter()
    .append("polyline")
    .attr("stroke", "black")
    .data(data.links.points)
    .attr("points", d => (d[0] + translatex) * scale, (d[1] + translatey) * scale)

but this gives me the error of unknown d. Since I do not (I notice now) fully understand how the first block of code works, I cannot see how to make this second block of code working. Are there any suggestions?

I ended up solving it as follows:

var link = svg
    .selectAll("polyline")
    .data(data.links)
    .enter().append("polyline")
    .attr("points",function(d) { 
        convertedpoints = d.points.map(function(d) {return [(d[0] + translatex) * 
scale, (d[1] + translatey) * scale]})
        return convertedpoints.join(" ");})
    .attr("stroke", "black")
    .attr("stroke-width",1)
    .attr("fill", "none")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM