javascript-d3How do I use JavaScript and D3 to create an SVG?
Using JavaScript and D3, we can create an SVG (Scalable Vector Graphic) with the following steps:
- Create a
<svg>
element in the DOM:
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 300);
This code creates a <svg>
element and appends it to the body of the HTML page. We set the width and height of the SVG to 500 and 300 respectively.
- Create shapes inside the
<svg>
element:
var rect = svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 50)
.attr("fill", "blue");
The code above creates a rectangle inside the <svg>
element and sets its attributes such as x and y coordinates, width and height, and fill color.
- Create text inside the
<svg>
element:
var text = svg.append("text")
.attr("x", 20)
.attr("y", 50)
.attr("fill", "red")
.text("Hello World!");
The code above creates a text element inside the <svg>
element and sets its attributes such as x and y coordinates and fill color. The text content is set to "Hello World!".
Helpful links
More of Javascript D3
- How do I use the z-index property with d3.js?
- How do I create a zoomable chart using d3.js?
- How can I use d3.js to create a zoom scale?
- How do I create a zoomable line chart using d3.js?
- How do I create an x and y axis using d3.js?
- How do I set up the x axis in d3.js?
- How do I use d3.js to create visualizations?
- How do I install and use D3.js with Yarn?
- How can I create a word cloud using d3.js?
- How can I use d3.js and neo4j together to create data visualizations?
See more codes...