How can I get a random plot of ellipses to be created using createElementNs, and be appended within a specific place of an svg?

Viewed 29

enter image description here

im using

setInterval(function(){randomX = Math.floor(Math.random() * 220) + 195;randomY = Math.floor(Math.random() * 180) + 90;var ellipse=document.createElementNS("http://www.w3.org/2000/svg", 'ellipse');document.querySelector("#Layer_1").appendChild(ellipse);ellipse.setAttribute('rx','5');ellipse.setAttribute('ry','5');ellipse.setAttribute('cx',randomX+'px');ellipse.setAttribute('cy',randomY+'px');ellipse.style.fill='red'},1000);

to generate the ellipses every second, but Im really wanting to append them within the lined area, and no where else. That area is a an svg child element with an ID of fillDots,

<polygon onmouseover="fillDots()" id="fillDots" class="cls-21" points="360.04 -1.44 175.7 2.74 139.85 53.71 293.96 280.3 427.91 102.55 360.04 -1.44"/><line class="cls-22" x1="294.65" y1="94.22" x2="286.3" y2="181.17"/>

Ive tried looking for ways to append an svg element within another svg child element but haven't found any solutions. I thought also maybe trying to use foreign object, but I would want to use the points of the lined area and foreign object is a square/rectangle. Any help would be awesome, thank you.

1 Answers

You can use isPointInFill():

If the new point is in fill paint the point.

Observation: there is also a isPointInStroke() method

setInterval(function () {
  let randomX = Math.floor(Math.random() * 220) + 195,
    randomY = Math.floor(Math.random() * 180) + 90;

  let point = Layer_1.createSVGPoint();
  point.x = randomX;
  point.y = randomY;

  if (fillDots.isPointInFill(point)) {
    //isPointInStroke
    let ellipse = document.createElementNS(
      "http://www.w3.org/2000/svg",
      "ellipse"
    );

    document.querySelector("#Layer_1").appendChild(ellipse);
    ellipse.setAttribute("rx", "5");
    ellipse.setAttribute("ry", "5");
    ellipse.setAttribute("cx", randomX + "px");
    ellipse.setAttribute("cy", randomY + "px");
    ellipse.style.fill = "red";
  }
}, 1000);
svg{border:solid}
<svg id="Layer_1" viewBox="135 -5 300 300" width="300">
<g id="g">
<polygon  id="fillDots" class="cls-21" points="360.04 -1.44 175.7 2.74 139.85 53.71 293.96 280.3 427.91 102.55 360.04 -1.44" stroke="black" stroke-width="5"/>
  </g>
</svg>

Related