SlideShare a Scribd company logo
Creating dynamic SVG elements in JavaScript
Blog Post link: http://jbkflex.wordpress.com/2011/06/21/creating-dynamic-svg-elements-in-javascript/


While I was working on a HTML5 project I found this problem of creating SVG (Scalable Vector Graphics) elements
dynamically in JavaScript. For example creating vector circles inside a for loop and adding them to the page. HTML5
supports inline SVG, so you can directly use <svg>your code</svg> inside <body> to create vector graphics. But I had the task of creating them
in the script. So I have put forward a small example and here is how to do it.
To create a vector circle of radius 50,

   var svgNS = "http://www.w3.org/2000/svg";




   var myCircle = document.createElementNS(svgNS,"circle");


   myCircle.setAttributeNS(null,"id","mycircle");


   myCircle.setAttributeNS(null,"cx",100);


   myCircle.setAttributeNS(null,"cy",100);


   myCircle.setAttributeNS(null,"r",50);

   myCircle.setAttributeNS(null,"fill","black");


   myCircle.setAttributeNS(null,"stroke","none");


where cx = x-coordinate of the center where you want the circle to be, similarly cy is the y-coordinate of the center.
Now that our circle is ready, we want to add it to the page, rather view it. Till now we did not add the circle to theDOM. It is important to note that
SVG elements when added to our HTML page becomes a part of the DOM, so later you can access the elements in JavaScript code and
manipulate their properties.
Since html5 supports inline SVG, so write this inside your body,

   <svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">


   </svg>


I have used an id with the svg tag. Access the SVG tag by its id in JavaScript code and then add the circle,

   document.getElementById("mySVG").appendChild(myCircle);


You should be able to see a black dark circle of radius 50 in your page at 100,100 from top left corner of the browser. Here is the full code that
you can use directly,

   <html>


   <head>


        <title>Dynamic Vector Circle</title>


        <script type="text/javascript">


              var svgNS = "http://www.w3.org/2000/svg";




              function createCircle()


              {


                    var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle, for
   rectangle use rectangle


                    myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);


                   myCircle.setAttributeNS(null,"cy",100);


                   myCircle.setAttributeNS(null,"r",50);


                   myCircle.setAttributeNS(null,"fill","black");


                   myCircle.setAttributeNS(null,"stroke","none");




                   document.getElementById("mySVG").appendChild(myCircle);


              }




        </script>


   </head>


   <body onload="createCircle();">


        <svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">


        </svg>


   </body>


   </html>


Similarly you can create other vector shapes like rectangles ,paths.
However, there is better option of doing all this. Creating dynamic vector shapes in JavaScript has been made very easy by
the Raphael JavaScript library. It is very lightweight and has lots of features like charts, complex vector shapes, image crop etc.

More Related Content

DOCX
Java script slideshow by karan chanana
PDF
How to create interactive infographics
PPTX
Geekspeak: Javascript
PDF
SVG for JS Oxford
KEY
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
PDF
JavaScript para Graficos y Visualizacion de Datos
KEY
Tools that get you laid
PDF
Railsbridge javascript
Java script slideshow by karan chanana
How to create interactive infographics
Geekspeak: Javascript
SVG for JS Oxford
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
JavaScript para Graficos y Visualizacion de Datos
Tools that get you laid
Railsbridge javascript

What's hot (7)

PDF
New Tools for Visualization in JavaScript - Sept. 2011
PPTX
Jquery image slider
PDF
Unobtrusive JavaScript
PDF
jQuery - 10 Time-Savers You (Maybe) Don't Know
PDF
Leaving Flatland: Getting Started with WebGL- SXSW 2012
PDF
jQuery Introduction
PPTX
dotnetConf2019 meetup in AICHI / Elmish
New Tools for Visualization in JavaScript - Sept. 2011
Jquery image slider
Unobtrusive JavaScript
jQuery - 10 Time-Savers You (Maybe) Don't Know
Leaving Flatland: Getting Started with WebGL- SXSW 2012
jQuery Introduction
dotnetConf2019 meetup in AICHI / Elmish
Ad

Similar to Creating dynamic SVG elements in JavaScript (20)

PPTX
SVG and the web
PDF
Drawing a Circle Three Ways: Generating Graphics for the Web
KEY
CSS3 Takes on the World
PDF
D3.js and SVG
PPTX
Лабораторная работа №1
PDF
Илья Пухальский (EPAM Systems)
KEY
SVG overview
KEY
Thats Not Flash?
PPT
STC Summit 2015 Hypergraphics for visual-first help
PPTX
Sara Soueidan: Styling and Animating Scalable Vector Graphics with CSS [CSSCo...
PPTX
Svcc 2013-d3
PPTX
SVCC 2013 D3.js Presentation (10/05/2013)
KEY
Web accessibility
PPTX
Introduction to HTML5 Canvas
PDF
Setting the Stage for SVG Animation
PPTX
Svg, canvas e animations in angular (3 maggio 2019)
PDF
I Can't Believe It's Not Flash
PDF
The Creative New World of CSS
PDF
Unlocking the full potential of SVG
PPTX
SVGD3Angular2React
SVG and the web
Drawing a Circle Three Ways: Generating Graphics for the Web
CSS3 Takes on the World
D3.js and SVG
Лабораторная работа №1
Илья Пухальский (EPAM Systems)
SVG overview
Thats Not Flash?
STC Summit 2015 Hypergraphics for visual-first help
Sara Soueidan: Styling and Animating Scalable Vector Graphics with CSS [CSSCo...
Svcc 2013-d3
SVCC 2013 D3.js Presentation (10/05/2013)
Web accessibility
Introduction to HTML5 Canvas
Setting the Stage for SVG Animation
Svg, canvas e animations in angular (3 maggio 2019)
I Can't Believe It's Not Flash
The Creative New World of CSS
Unlocking the full potential of SVG
SVGD3Angular2React
Ad

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Cloud computing and distributed systems.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Empathic Computing: Creating Shared Understanding
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Network Security Unit 5.pdf for BCA BBA.
Teaching material agriculture food technology
NewMind AI Weekly Chronicles - August'25 Week I
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Cloud computing and distributed systems.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Empathic Computing: Creating Shared Understanding
Advanced methodologies resolving dimensionality complications for autism neur...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Unlocking AI with Model Context Protocol (MCP)
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Electronic commerce courselecture one. Pdf
Chapter 3 Spatial Domain Image Processing.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Approach and Philosophy of On baking technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
The AUB Centre for AI in Media Proposal.docx
Network Security Unit 5.pdf for BCA BBA.

Creating dynamic SVG elements in JavaScript

  • 1. Creating dynamic SVG elements in JavaScript Blog Post link: http://jbkflex.wordpress.com/2011/06/21/creating-dynamic-svg-elements-in-javascript/ While I was working on a HTML5 project I found this problem of creating SVG (Scalable Vector Graphics) elements dynamically in JavaScript. For example creating vector circles inside a for loop and adding them to the page. HTML5 supports inline SVG, so you can directly use <svg>your code</svg> inside <body> to create vector graphics. But I had the task of creating them in the script. So I have put forward a small example and here is how to do it. To create a vector circle of radius 50, var svgNS = "http://www.w3.org/2000/svg"; var myCircle = document.createElementNS(svgNS,"circle"); myCircle.setAttributeNS(null,"id","mycircle"); myCircle.setAttributeNS(null,"cx",100); myCircle.setAttributeNS(null,"cy",100); myCircle.setAttributeNS(null,"r",50); myCircle.setAttributeNS(null,"fill","black"); myCircle.setAttributeNS(null,"stroke","none"); where cx = x-coordinate of the center where you want the circle to be, similarly cy is the y-coordinate of the center. Now that our circle is ready, we want to add it to the page, rather view it. Till now we did not add the circle to theDOM. It is important to note that SVG elements when added to our HTML page becomes a part of the DOM, so later you can access the elements in JavaScript code and manipulate their properties. Since html5 supports inline SVG, so write this inside your body, <svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> I have used an id with the svg tag. Access the SVG tag by its id in JavaScript code and then add the circle, document.getElementById("mySVG").appendChild(myCircle); You should be able to see a black dark circle of radius 50 in your page at 100,100 from top left corner of the browser. Here is the full code that you can use directly, <html> <head> <title>Dynamic Vector Circle</title> <script type="text/javascript"> var svgNS = "http://www.w3.org/2000/svg"; function createCircle() { var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle, for rectangle use rectangle myCircle.setAttributeNS(null,"id","mycircle");
  • 2. myCircle.setAttributeNS(null,"cx",100); myCircle.setAttributeNS(null,"cy",100); myCircle.setAttributeNS(null,"r",50); myCircle.setAttributeNS(null,"fill","black"); myCircle.setAttributeNS(null,"stroke","none"); document.getElementById("mySVG").appendChild(myCircle); } </script> </head> <body onload="createCircle();"> <svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> </body> </html> Similarly you can create other vector shapes like rectangles ,paths. However, there is better option of doing all this. Creating dynamic vector shapes in JavaScript has been made very easy by the Raphael JavaScript library. It is very lightweight and has lots of features like charts, complex vector shapes, image crop etc.