- Using SVG with JavaScript? [Tutorial]
- Create SVG Image in JavaScript
- Method-1: Using the createElementNS method
- Methpd-2: Using string of SVG Code with innerHTML
- Method-3: Using third-party libraries
- Create JavaScript SVG Animation
- Summary
- References
- Leave a Comment Cancel reply
- JavaScript Tutorial
- Scripting
- Preventing default behavior in event code
- Using eventListeners with objects
- Inter-document scripting: referencing embedded SVG
- Inter-document scripting: calling JavaScript functions
- setProperty has three parameters
- Links
- Found a content problem with this page?
Using SVG with JavaScript? [Tutorial]
JavaScript can be used to create and manipulate SVG (Scalable Vector Graphics) images, which are a type of vector image that can be resized without losing quality. SVG images are composed of shapes and paths and can be created using a variety of tools, including text editors, vector editing software, and JavaScript libraries.
Developed by the W3C, we can create scalable images that are lossless using the element on our webpage. However, if we want to create SVG image using JavaScript, we have specific methods or string approaches we can apply. In this article, we will discuss a couple of ways to create SVG image using SVG elements.
Create SVG Image in JavaScript
We can create SVG images in JavaScript using different approaches which include creating the SVG using the built-in methods to SVG code strings.
Method-1: Using the createElementNS method
One way to create an SVG image using JavaScript is to create an SVG element via the createElementNS method and then append child elements, such as , , or , to the element. These child elements are used to create the shapes and paths that make up the image.
To illustrate how to create SVG image using JavaScript, we will create a simple square with a red color fill via the rect attribute. Using the setAttribute() method, we can set position and size of the rect element. Finally, we append the SVG to the HTML document using the appendChild() node method.
Methpd-2: Using string of SVG Code with innerHTML
Another way to create an SVG image using JavaScript is to create a string of SVG code and then use innerHTML to insert it into an HTML element. This can be useful for creating complex images with multiple shapes and paths.
Method-3: Using third-party libraries
You can also use JavaScript libraries such as SVG.js, D3.js, Raphaël, and Snap.svg to create and manipulate SVG images. These libraries provide a wide range of tools and methods for creating, styling, and animating SVG images, and can be useful for creating interactive and animated data visualizations.
To show you how to make use of third-party using the SVG.js library. Before we can make use of the library, we can add the library via a CDN as below
After, we can then include the library within our code environment and make use of its built-in method such as SVG() and rect() . Here is the code snippet to achieve a red box using the SVG.js library
The addTo() method adds the SVG image created to the HTML document body.
Create JavaScript SVG Animation
There are multiple ways to animate SVG elements in JavaScript. Some of the most common methods include:
- SMIL (Synchronized Multimedia Integration Language) — It is a specification for handling animation in SVG. SMIL allows you to animate the attributes of SVG elements using a simple set of elements and attributes. However, support for SMIL is limited, and it is not supported in some modern browsers.
- CSS — You can use CSS to animate SVG elements by applying CSS animations and transitions to SVG elements. This method is widely supported and works well for simple animations.
- JavaScript — You can use JavaScript to animate SVG elements by manipulating the attributes of SVG elements directly or by using a JavaScript animation library like GreenSock.
Here’s an example that animates the width and height of an SVG rectangle element using CSS:
In this example, the width and height of the rectangle element will be animated over 2 seconds when the button is clicked.
You can also use JavaScript animation libraries like GreenSock to create more complex animations.
This example use GreenSock library to animate width and height of rectangle on load.
In addition, you can also use the animate method of the SVG elements to animate them.
This example uses the animate method to animate the width and height of the rectangle over 2 seconds.
Summary
JavaScript can be used to create and manipulate SVG images, which are a type of vector image that can be resized without losing quality. SVG images can be created by creating an SVG element and then appending child elements, such as , , or , to the element. You can also create SVG images by creating a string of SVG code and then using innerHTML to insert it into an HTML element.
And there are various libraries such as SVG.js, D3.js, Raphaël, and Snap.svg that can help you to create and manipulate SVG images in a more efficient and convenient way. These libraries provide a wide range of tools and methods for creating, styling, and animating SVG images, and can be useful for creating interactive and animated data visualizations.
References
JavaScript provides a powerful toolset for creating and manipulating SVG images. You can use plain JavaScript to create an SVG image, or use some libraries such as SVG.js, D3.js, Raphaël, and Snap.svg to create and manipulate SVG images in a more efficient and convenient way. These libraries provide a wide range of tools and methods for creating, styling, and animating SVG images, and can be useful for creating interactive and animated data visualizations.
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
JavaScript Tutorial
- Beginner Guide
- Define Global Variable
- Working with Object Literals
- Working with Template Literals
- Classes Overview
- Subclass Examples
- Iterators and Generators
- Error Handling
- Date Formatting
- parseFloat()
- Array.pop()
- Array.slice()
- Array.unshift()
- Array.join()
- Array.findIndex()
- Array Slicing Methods
- Remove Element from Array
- Check Array is Empty
- Create Unique Array of Objects
- Convert Array to String
- String.toLowerCase()
- String.toString()
- String.trimEnd()
- String.trim()
- String.replaceAll()
- String.startsWith()
- replaceWith()
- String.indexOf()
- replaceAll() with regex
- Check if String is Number
- Check string contains spaces
- Convert String to Boolean
- Check String contains Substring
- Compare Strings
- Math.acos()
- Math.abs()
- Math.asin()
- Math.atan()
- Math.cbrt()
- Math.ceil()
- Math.cos()
- Math.floor()
- Math.fround()
- Math.hypot()
- Math.log()
- Math max()
- Math.power()
- Math.random()
- Math.toRadians()
- Nested Function
- Arrow Function
- Optional Parameters
- The arguments Object
- Calling Vs Invoking a Function
- Call a function every second
- Using function as Values
- Chaining Functions
- if statement
- Handling Special Characters
- hide() Method
- Set.add()
- Remove Element from Set
- DOM Selector Methods
- Find Elements in DOM
- Remove DOM Element
- Replace DOM Element
- Get DOM Element Width
- addEventListener()
- querySelector()
- getBoundingClientRect()
- NodeList
- Node.insertBefore()
- Event Bubbling
- Parse JSON File
- Parse YAML File
- Parse CSV File
- async function
- await
- Exponentiation (**)
- Bitwise XOR (^)
- Nullish Coalescing Operator (??)
- Double Exclamation Mark (!!)
- Spread Operator (. )
- Destructuring assignment
- instanceof Operator
- Access map with index
- Check map size
- Sort map by value
- Sort by date
- Add days to date
- date/time field value out of range
- Promise Thenable Object
- Promise.all()
- Promise.resolve()
- Promise.race()
- Promise.reject()
- Chaining Promises
- Keyboard Events
- Mouse Events
- Singleton Pattern
- Mediator Pattern
- Observer Pattern
- Factory Pattern
Scripting
One can override default browser behaviors with the evt.preventDefault() method, add event listeners to objects with the syntax element.addEventListener(event, function, useCapture) , and set element properties with syntax like svgElement.style.setProperty(«fill-opacity», «0.0», «») . Note the existence of all three arguments setting properties.
Preventing default behavior in event code
When writing drag and drop code, sometimes you’ll find that text on the page gets accidentally selected while dragging. Or if you want to use the backspace key in your code, you want to override the browser’s default behavior when the backspace key is pressed, which is to go back to the previous page. The evt.preventDefault() method lets you do this.
Using eventListeners with objects
The methods addEventListener() and removeEventListener() are very useful when writing interactive SVG. You can pass an object that implements the handleEvent interface as the second parameter to these methods.
function myRect(x, y, w, h, message) this.message = message; this.rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); this.rect.setAttributeNS(null, "x", x); this.rect.setAttributeNS(null, "y", y); this.rect.setAttributeNS(null, "width", w); this.rect.setAttributeNS(null, "height", h); document.documentElement.appendChild(this.rect); this.rect.addEventListener("click", this, false); this.handleEvent = (evt) => switch (evt.type) case "click": alert(this.message); break; > >; >
Inter-document scripting: referencing embedded SVG
When using SVG within HTML, Adobe’s SVG Viewer 3.0 automatically includes a window property called svgDocument that points to the SVG document. This is not the case for Mozilla’s native SVG implementation; therefore, using window.svgDocument does not work in Mozilla. Instead, you can use
const svgDoc = document.embeds["name_of_svg"].getSVGDocument();
to get a reference to an embedded SVG document instead.
The best way to get access to the Document representing an SVG document is to look at HTMLIFrameElement.contentDocument (if the document is presented in an ) or HTMLObjectElement.contentDocument (if the document is presented in an element), like this:
const svgDoc = document.getElementById("iframe_element").contentDocument;
In addition, the , , and elements offer a method, getSVGDocument() , which returns the XMLDocument representing the element’s embedded SVG or null if the element doesn’t represent an SVG document.
You can also use document.getElementById(«svg_elem_name»).getSVGDocument() , which gives the same result.
Note: You may find documentation referring to an SVGDocument interface. Prior to SVG 2, SVG documents were represented using that interface. However, SVG documents are now represented using the XMLDocument interface instead.
Inter-document scripting: calling JavaScript functions
When calling a JavaScript function that resides in the HTML file from an SVG file that is embedded in an HTML document, you should use parent.functionname() to reference the function. Although the Adobe SVG viewer plugin allows the use of functionname() , it’s not the preferred way to do things.
Note: According to the SVG wiki the «parent» JS variable is broken in Adobe’s SVG version 6 preview plugin. The suggested workaround is to use «top» instead of «parent» . Since it is a beta version of their plugin, we can probably safely ignore this.
More information and some examples can be found on the SVG wiki inter-document scripting page.
setProperty has three parameters
The function svgElement.style.setProperty(«fill-opacity», «0.0») throws a DOMException — SYNTAX ERR in Mozilla. This behavior is specified by the W3C in the DOM Level 2 Style Specification. The function setProperty is defined as a function with three parameters. The above can be replaced with ‘svgElement.style.setProperty(«fill-opacity», «0.0», «»)’ , which is standards compliant.
Links
Found a content problem with this page?