swam
swam

Reputation: 303

d3 Javascript - Draw polygon

I have an SVG canvas that I want to be able to click points and draw a polygon. I have the following code to do that:

var clicks = [];
    function polyClick(){

        var x = event.clientX;
        var y = event.clientY;
        var point = document.getElementById("num").value;

        clicks.push.apply(clicks, [x,y]);
        drawPoly(clicks)
        function drawPoly(params){

        d3.select(".p").remove();
        mySVG.append("svg:polygon")
        .style("fill", "red")
        .style("stroke-width", "1")
        .classed("p", true)
        .attr("points", params + " ");  //This LINE

        }            

    }

The line marked "This LINE" give me the correct x and y coordinates but in the format of "21,50,60,70,90,100". What I need is for the coordinates in the array are added as sets such as "21,50 60,70 90,100". Any idea on how to go about removing the comma in between each coordinate?

BONUS: Can anyone tell me exactly what this line does?

drawPoly(clicks)
function drawPoly(params)

I found it as a suggestion to use array values as a parameter to a function but I don't fully understand how that is working. I'm using "drawPoly" before the function is even declared.

Thanks for any and all help!

Upvotes: 0

Views: 1531

Answers (1)

Gilsha
Gilsha

Reputation: 14591

Function definitions are processed during compilation and expressions (like function call) are processed during execution. This is why in JavaScript function definition and function call order does not matter.

Code Explanation:

function drawPoly(params){
    d3.select(".p").remove(); //'p' is the class name of polygon. This line deletes the polygon if exists.
    mySVG.append("svg:polygon") //Appends a new polygon with the calculated position attributes.
      .style("fill", "red")
      .style("stroke-width", "1")
      .classed("p", true) //Sets classname as p
      .attr("points", params);
}    

The code seems to be working with the current format of coordinates. Below is the working code snippet.

Try out by clicking more than 3 points as the coordinates of polygon.

var mySVG = d3.select("#container").append("svg").attr({
  width: 500,
  height: 200
});
mySVG.on('click', polyClick);
var clicks = [];

function polyClick() {

  var x = event.clientX;
  var y = event.clientY;

  clicks.push.apply(clicks, [x, y]);
  drawPoly(clicks)

  function drawPoly(params) {
    d3.select(".p").remove();
    mySVG.append("svg:polygon")
      .style("fill", "red")      
      .style("stroke-width", "1")
      .classed("p", true)
      .attr("points", params + " ");

  }

}
svg {
  background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="container">
</div>

Upvotes: 2

Related Questions