SVG, or Scalable Vector Graphics, is an XML-based vector graphics format used for creating 2D graphics. As it is an XML format, SVG can be manipulated by JavaScript in much the same way as HTML.
To demonstrate how to use JavaScript for SVG manipulation, we will walk-through a step-by-step guide using an example.
Here's the layout of the HTML & SVG:
<!DOCTYPE html>
<html>
<body>
<svg id="mySVG" width="200" height="200">
<circle id="myCircle" cx="50" cy="50" r="50" fill="blue" />
</svg>
<button onclick="changeCircle()">Change Circle</button>
<script src="script.js"></script>
</body>
</html>
Ask your specific question in Mate AI
In Mate you can connect your project, ask questions about your repository, and use AI Agent to solve programming tasks
In this example, we have an SVG element with one child element, a circle. The circle has a center (cx, cy)
at (50, 50)
, a radius of 50
, and a fill
color of blue
.
JavaScript File (script.js):
function changeCircle() {
var myCircle = document.getElementById('myCircle');
myCircle.setAttribute('cx', 100);
myCircle.setAttribute('cy', 100);
myCircle.setAttribute('r', 25);
myCircle.style.fill = 'red';
}
In this JavaScript file, we defined a function changeCircle()
that updates the cx
, cy
, r
attributes and the fill
style of the circle.
This function:
- Uses
document.getElementById()
to select the circle element. - Uses
setAttribute()
to change thecx
,cy
, andr
(radius) attributes of the circle. - Directly modifies the
style.fill
property to change the circle's fill color.
Now, when the 'Change Circle' button is clicked, it triggers the changeCircle()
function. The blue circle at (50, 50)
with a radius 50
will move to the new coordinate (100, 100)
, shrink to a radius of 25
, and change its color to red
.
This is a basic example of manipulating SVG with JavaScript. You can do many more complex manipulations by changing SVG attributes and styles, or even by adding, removing, or modifying SVG elements in the DOM. Functions and events can be used to make these changes in response to user input or other triggers.
AI agent for developers
Boost your productivity with Mate:
easily connect your project, generate code, and debug smarter - all powered by AI.
Do you want to solve problems like this faster? Download now for free.