SlideShare une entreprise Scribd logo
1  sur  2
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.

Contenu connexe

Tendances (7)

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

Similaire à Creating dynamic SVG elements in JavaScript

Илья Пухальский (EPAM Systems)
Илья Пухальский (EPAM Systems)Илья Пухальский (EPAM Systems)
Илья Пухальский (EPAM Systems)
Ontico
 
Web accessibility
Web accessibilityWeb accessibility
Web accessibility
Eb Styles
 

Similaire à Creating dynamic SVG elements in JavaScript (20)

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

Dernier

Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
UK Journal
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Dernier (20)

Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Oauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoftOauth 2.0 Introduction and Flows with MuleSoft
Oauth 2.0 Introduction and Flows with MuleSoft
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4j
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 

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.