SVG provides various ways to implement interactive features, making it a powerful tool for creating interactive graphics:
1. Event Listeners SVG elements support standard DOM events and can have event listeners added directly to SVG elements.
HTML Attribute Method:
svg<svg width="200" height="200"> <circle cx="100" cy="100" r="50" fill="blue" onclick="handleClick()" onmouseover="handleMouseOver()" onmouseout="handleMouseOut()" /> </svg> <script> function handleClick() { console.log('Circle clicked!'); } function handleMouseOver() { console.log('Mouse over circle'); } function handleMouseOut() { console.log('Mouse out of circle'); } </script>
JavaScript addEventListener Method:
javascriptconst circle = document.querySelector('circle'); circle.addEventListener('click', function() { this.setAttribute('fill', 'red'); }); circle.addEventListener('mouseover', function() { this.setAttribute('fill', 'green'); }); circle.addEventListener('mouseout', function() { this.setAttribute('fill', 'blue'); });
2. CSS Interaction Use CSS pseudo-classes and transition effects to implement interaction.
svg<svg width="200" height="200"> <style> .interactive-circle { fill: blue; transition: all 0.3s ease; cursor: pointer; } .interactive-circle:hover { fill: red; r: 60; } .interactive-circle:active { fill: green; } </style> <circle class="interactive-circle" cx="100" cy="100" r="50" /> </svg>
3. JavaScript Dynamic Manipulation Dynamically modify SVG attributes and styles via JavaScript.
javascript// Modify attributes const circle = document.querySelector('circle'); circle.setAttribute('cx', '150'); circle.setAttribute('fill', 'purple'); // Modify styles circle.style.fill = 'orange'; circle.style.opacity = '0.5'; // Add new elements const svg = document.querySelector('svg'); const newCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); newCircle.setAttribute('cx', '50'); newCircle.setAttribute('cy', '50'); newCircle.setAttribute('r', '30'); newCircle.setAttribute('fill', 'yellow'); svg.appendChild(newCircle);
4. Drag Interaction Implement drag functionality for SVG elements.
javascriptlet selectedElement = null; let offset = { x: 0, y: 0 }; function getMousePosition(evt) { const CTM = svg.getScreenCTM(); return { x: (evt.clientX - CTM.e) / CTM.a, y: (evt.clientY - CTM.f) / CTM.d }; } function startDrag(evt) { selectedElement = evt.target; offset = getMousePosition(evt); offset.x -= parseFloat(selectedElement.getAttribute('cx')); offset.y -= parseFloat(selectedElement.getAttribute('cy')); } function drag(evt) { if (selectedElement) { evt.preventDefault(); const coord = getMousePosition(evt); selectedElement.setAttribute('cx', coord.x - offset.x); selectedElement.setAttribute('cy', coord.y - offset.y); } } function endDrag(evt) { selectedElement = null; } const svg = document.querySelector('svg'); svg.addEventListener('mousedown', startDrag); svg.addEventListener('mousemove', drag); svg.addEventListener('mouseup', endDrag); svg.addEventListener('mouseleave', endDrag);
5. Animation Interaction Combine animation and interaction for more complex effects.
javascriptconst circle = document.querySelector('circle'); circle.addEventListener('click', function() { this.style.transition = 'all 0.5s ease'; this.style.transform = 'scale(1.5)'; setTimeout(() => { this.style.transform = 'scale(1)'; }, 500); });
6. Accessibility Interaction Add accessibility support for SVG.
svg<svg width="200" height="200" role="img" aria-labelledby="svg-title svg-desc"> <title id="svg-title">Interactive Circle</title> <desc id="svg-desc">Click the circle to change its color</desc> <circle cx="100" cy="100" r="50" fill="blue" tabindex="0" onclick="changeColor(this)" onkeydown="handleKeydown(event, this)" /> </svg> <script> function changeColor(element) { const colors = ['blue', 'red', 'green', 'yellow', 'purple']; const currentColor = element.getAttribute('fill'); const currentIndex = colors.indexOf(currentColor); const nextIndex = (currentIndex + 1) % colors.length; element.setAttribute('fill', colors[nextIndex]); } function handleKeydown(event, element) { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); changeColor(element); } } </script>
Best Practices:
- Prioritize CSS for simple interactions
- Use JavaScript for complex interactions
- Add appropriate accessibility support
- Consider mobile touch events
- Optimize performance, avoid frequent DOM operations