Thursday, December 5, 2019

D3 : Creating SVG element



Below is how a line can be drawn

    var width = 500;
                var height = 500;

                //Create SVG element
                var svg = d3.select("body")
                .append("svg")
                .attr("width", width)
                .attr("height", height);

                //Create line element inside SVG
    svg.append("line")
       .attr("x1", 100)
       .attr("x2", 500)
       .attr("y1", 50)
       .attr("y2", 50)
       .attr("stroke", "black")

Below is how a rentangle can be made


                    var width = 500;
                    var height = 500;

                    //Create SVG element
                    var svg = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", height);

                    //Create and append rectangle element
    svg.append("rect")
            .attr("x", 0)
            .attr("y", 0)
            .attr("width", 200)
            .attr("height", 100)


Below is how a circle can be made

//Create SVG element
    var svg = d3.select("body")
                .append("svg")
                .attr("width", width)
                .attr("height", height);

                    //Append circle
    svg.append("circle")
       .attr("cx", 250)
       .attr("cy", 50)
       .attr("r", 50)



Below is how a group is made

//Create SVG element
var svg = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", height);
   
//Create group element
var g = svg.append("g")
           .attr("transform", function(d, i) {
                    return "translate(0,0)";
           });

//Create and append ellipse element into group
var ellipse = g.append("ellipse")
               .attr("cx", 250)
               .attr("cy", 50)
               .attr("rx", 150)
               .attr("ry", 50)
               .append("text")

//Create and append text element into group
g.append("text")
 .attr("x", 150)
 .attr("y", 50)
 .attr("stroke", "#fff")
 .text("This is an ellipse!");



Below is how an svg element can be prettified

g.append("text")
 .attr("x", 140)
 .attr("y", 50)
 .attr("stroke", "steelblue")
 .attr("font-family", "sans-serif")
 .attr("font-size", "24px")
 .text("I am a pretty ellipse!");



References:
https://www.tutorialsteacher.com/d3js/create-svg-elements-in-d3js

No comments:

Post a Comment