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

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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.