01: <svg version="1.1" baseProfile="full" 02: xmlns="http://www.w3.org/2000/svg" 03: width="600px" height="400px" viewBox="0 0 600 400" 04: stroke="black" stroke-width="0.5px" onclick="makeDisk(evt)"> 05: 06: <script> 07: // <![CDATA[ 08: 09: var svgNS = "http://www.w3.org/2000/svg"; 10: 11: function makeDisk(evt){ 12: 13: // Get the mouse location: 14: var xclick = evt.clientX; 15: var yclick = evt.clientY; 16: 17: // Create a new disk and set its attributes: 18: var newcircle = document.createElementNS(svgNS, "circle"); 19: newcircle.setAttributeNS(null, "cx", xclick); 20: newcircle.setAttributeNS(null, "cy", yclick); 21: newcircle.setAttributeNS(null, "r", 10); 22: var randomhue=Math.floor(Math.random()*360); 23: newcircle.setAttributeNS(null, "fill", "hsl("+randomhue+",100%,50%)"); 24: 25: document.rootElement.appendChild(newcircle); 26: } 27: 28: // ]]> 29: </script> 30: 31: </svg>
Lines 14 and 15 get the coordinates of the mouse click. It is important to note that these are the coordinates in pixels from the left and top edges of the graphic, which may not always be what you want as we note in the next example.
In addition to onclick, there are other attributes of SVG elements (or tags) which give rise to mouse interactions. These are listed below:
You can extract the location of the mouse in any of the above in the same way.