我正在尝试使用elementFromPoint在SVG路径内创建随机点,以按照答案here来检查它们是否在路径内,如下所示:
(function() {
var randomPoint = function(svg, bbox){
var s = svg.createSVGPoint()
s.x = (1 * bbox.x + (Math.random() * bbox.width)),
s.y = (1 * bbox.y + (Math.random() * bbox.height))
return s
}
var path = document.querySelector('#thePath');
var svg = document.querySelector('svg');
var svgNS = svg.namespaceURI;
var p = document.querySelector('#thePath');
p.setAttribute('fill', 'grey');
var bbox = p.getBBox();
var m = document.querySelector('#layer1').getCTM() // this is the overall grouping - no transforms
for (var i = 0; i < 2000; i++) {
var point = randomPoint(svg, bbox); // ..matrixTransform(m);
if(document.elementFromPoint(point.x, point.y) === p) {
var c = document.createElementNS(svgNS, 'ellipse');
c.setAttribute('cx', point.x);
c.setAttribute('cy', point.y);
c.setAttribute('ry', 3);
c.setAttribute('rx', 3);
c.setAttribute('fill', '#aa000088');
svg.appendChild(c);
}
}
})();
但是有两个问题:
我应该怎么做?
Codepen here