Это моё решение этого вопроса.
Основная идея заключается в том, что при нажатии все фигуры нечувствительны к мыши.Также счетчик n
запускается с 0. Затем одна за другой каждая фигура становится чувствительной к мыши.Если мышь находится внутри фигуры, то счетчик n
увеличивается на единицу: n++
.
Надеюсь, это поможет.
let m = {};// mouse
let shapes = Array.from(document.querySelectorAll(".shape"));
svg.addEventListener("click", e => {
let n = 0;// a counter
m = oMousePos(e);// thr mouse position on click
shapes.map(s=>{
// all the shapes are insensitive to the mouse
shapes.map(_s=>{_s.style.pointerEvents = "none";})
// this shape is the only one sensitive to the mouse in this moment
s.style.pointerEvents = "all";
// detecting if the mouse is inside the shape
let elmt = document.elementFromPoint(m.x, m.y);
// if it is and the element has className.baseVal == "shape"
if(elmt.className.baseVal == "shape"){
//increase tho counter
n++
};
});
//use the counter
console.log(n);
});
function oMousePos(evt) {
return {
x: evt.clientX,
y: evt.clientY
};
}
svg {
border: 1px solid;
display: block;
margin: 0 auto;
}
.shape {
mix-blend-mode: multiply;
}
<svg id="svg" width="500" height="400" translate="45, 45">
<ellipse class="shape" cx="145" cy="125" rx="88" ry="20" fill="#aaa"></ellipse>
<circle class="shape" cx="175" cy="175" r="88" fill="#bbb"></circle>
<ellipse class="shape" cx="225" cy="125" rx="88" ry="55" fill="#ccc"></ellipse>
<circle class="shape" cx="275" cy="275" r="77" fill="#ddd"></circle>
</svg>