Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Create Circles and Rects in the SVG DOM

    htmlHTML 5

    In this lesson we go over how to draw basic shapes in SVG using the coordinate system: circles, ellipses, squares and rectangles, and rounded rectangles.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Drawing geometric primitives in an SVG take a few attributes depending on the shape. We're going to start off with the most basic of these, circles, ellipses, and rectangles. To draw a circle, all you really need is a radius.

    As we specify a radius here, a circle is drawn with the default coordinates of x at zero and y at zero. Typically, we want to plot a circle somewhere in the space of a viewbox. You can imagine that the viewbox makes a grid that scales along with the SVG, visualized here.

    To plot the circle, we'll define a Cx that specifies the center of the circle along the x-axis, and a Cy value, which plots the center along the y-axis. If we wanted the circle to be an ellipse instead, and have an uneven shape, we would change the element name circle into ellipse.

    We'd then update the R value into two values, Rx and Ry. Now, it can expand or contract in any direction. If I'd like it to be plotted to different coordinates, I simply change the Cx or Cy values, and it updates in position.

    Now, we have four values that are very similar to a square or rectangle. Both are defined by the rect element. A rect element has an x value, a y value, a width, and a height. If I'd like this rectangle to have rounded corners, I'd pass in an Rx and Ry value. These create rounded edges.