简体   繁体   English

如何获得要使用 createElementNs 创建的椭圆的随机 plot,并附加到 svg 的特定位置?

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

在此处输入图像描述

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.每秒生成椭圆,但我真的想在衬里区域内 append 他们,没有别的地方。 That area is a an svg child element with an ID of fillDots,该区域是一个 ID 为 fillDots 的 svg 子元素,

<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.我尝试在另一个 svg 子元素中寻找 append 和 svg 元素的方法,但没有找到任何解决方案。 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.我想也可能尝试使用外国 object,但我想使用线条区域的点,而外国 object 是正方形/矩形。 Any help would be awesome, thank you.任何帮助都会很棒,谢谢。

You can use isPointInFill() :您可以使用isPointInFill()

If the new point is in fill paint the point.如果新点在填充中,请绘制该点。

Observation: there is also a isPointInStroke() method观察:还有一个isPointInStroke()方法

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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