How to create an interactive grid of triangles using html, svg?

I have already created a grid of triangles:

svg { margin-left: 0px; margin-right: -60px; padding: 0; } 
 <div data-bind="foreach: Grid"> <div data-bind="foreach: $data.rowData"> <!-- ko if: $data.owner() === 0 && ($data.pos[0] + $data.pos[1])%2 === 0--> <svg height="103.92" width="120"> <polygon class="" points="60,0 0,103.92 120,103.92" style="fill:grey;" data-bind="click: $root.test.bind($data, $data)" /> </svg> <!-- /ko --> <!-- ko if: $data.owner() === 0 && ($data.pos[0] + $data.pos[1])%2 === 1--> <svg height="103.92" width="120"> <polygon class="" points="0,0 120,0 60,103.92" style="fill:grey;" data-bind="click: $root.test.bind($data, $data)" /> </svg> <!-- /ko --> </div> </div> 

My problem is that only the left half of the triangles is interactive. I think this is due to the (still rectangular) shape of the svg element. But I do not know how to fix it. Is there a way to make every triangle clickable in the entire area?

+4
source share
2 answers

At the moment, all of your individual SVGs overlap with each other, and any click that skips the triangle will be swallowed by the parent <svg> element.

The cleanest solution is to put all your polygons in one big SVG. However, there is another way to solve the problem using the pointer-events property.

Set pointer-events="none" to the <svg> elements so that clicks pass through them. But you will also need to set explicit pointer-events="fill" on your polygons, because otherwise they will inherit "none" from their parent SVGs.

 var output = document.getElementById("output"); document.getElementById("red").addEventListener("click", function(e) { output.textContent = "red"; }); document.getElementById("green").addEventListener("click", function(e) { output.textContent = "green"; }); 
 svg { position: absolute; top: 0; left: 0; pointer-events: none; } polygon { pointer-events: fill; } #output { margin-top: 120px; } 
 <svg width="100px" height="100px"> <polygon points="0,0,100,0,100,100" fill="red" id="red"/> </svg> <svg width="100px" height="100px"> <polygon points="0,0,100,100,0,100" fill="green" id="green"/> </svg> <div id="output"></div> 
+5
source

You should use one svg tag with two polygons inside it. Thus, Square svg elements will not overlap:

 polygon { fill: grey; } polygon:hover { fill: #000; } 
 <svg height="103.92" width="185"> <polygon points="60,0 0,103.92 120,103.92" /> <polygon points="65,0 185,0 125,103.92" /> </svg> 
+2
source

Source: https://habr.com/ru/post/1237550/


All Articles