Thursday 10 December 2020

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?



from drawing SVG polylines in a loop using javascript

No comments:

Post a Comment