Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas id="square"></canvas>

<canvas id="rectangle"></canvas>
<canvas id="circle"></canvas>
<br>
<canvas id="triangle"></canvas>
<canvas id="line"></canvas>
<canvas id="words"></canvas>


              
            
!

CSS

              
                #square, #rectangle, #circle, #line, #words{
border: 1px solid #aaa;
margin-left: 5%;
}
              
            
!

JS

              
                // Canvas : Basics

/*
  Now that we're familiar with the basic syntax necessary to draw shapes and test using HTML canvas, 
  
  we can begin looking at the syntax to do just that, draw shapes and text using HTML canvas.
  
  We'll start with basic shapes, like a square, circle, triangle, etc. and then move on to more complex things, such as drawing text.
  
       /////////////////////// Basic Shapes //////////////////////////
       
  1. Square
  
    First we'll set up our canvas syntax. If you look at our HTML tab, you can see we've created our canvas element with the ID of 'square'.

    We then set up the association to the HTML element within our javascript code so that we can use the 2d methods and draw on the canvas, like so:
 */

    let canvas1 = document.getElementById("square");
    // Next we specify the height and width of our canvas. Typically we set this to the viewport height and width for good practice,
    // but in this case we're going to be drawing multiple shapes in multiple different canvases, so we will specify a precise height and width of 400 pixels:
    canvas1.height = 400;
    canvas1.width = 400;
    // Now we can set the context of our canvas to 2d, and then we can begin creating the shape!
    let draw1 = canvas1.getContext("2d");
    // To draw a square in HTML canvas, we are going to implement the rect() method
    /*
        The rect() method is a method of the 2D Canvas API that allows us to easily draw squares and rectangles 
        
        The rect() method takes 4 parameters: rect(x, y, width, height)
            1. x: this is the x-axis coordinate of the rectangle's starting point, 
                  meaning at which point on the x axis, (or how far left or right), of the canvas should the rectangle begin?
            
            2. y: this is the y-axis coordinate of the rectangle's starting point, 
                  meaning at which point on the y axis, (or how high or low), of the canvas should the rectangle begin?
            
            3. width: provide a value for the width you want the rectangle to be
           
            4. height: provide a value for the height you want the rectangle to be
        
        (rect() documentation: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/rect)
    */
    // We now use the rect(x, y, width, height) method to draw a square. 
    // Going back to basic shapes in elementary school, we use the rectangle method for a square because every square is a rectangle, though not all rectangles are squares.
    // This square is offset 20 pixels on the x axis, and 20 pixels on the y axis, meaning it will have a starting position that is somewhat padded over to the right and padded upwards as well
    // To make a rectangle a square, the width and height must be equal, thus we set these values to be equivalent:
    draw1.rect(20, 20, 200, 200);
    // finally, to make our square appear, we call the stroke method to draw our square:
    draw1.stroke(); 

   // There are lots of methods we can use to alter and customize the look and shape of the square, one of which we will cover now:
  /*
        Fill:
          We can use two methods in the 2D Canvas API to either 1. fill an existing square/rectangle/other shape with a specified color, or 2. draw a new rectangle that comes filled in with a specified color
          We achieve these two options by use of the .fill() method and the .fillRect() method, both of which rely on a variable being set first:
          
          Before we can implement either of the two methods mentioned, we have to first declare a fillstyle for our drawing variable:
  */      draw1.fillStyle = "purple";
  /*      Now we can look at our two methods:
            1. .fill() : this method fills the path with the set fillStyle of the drawing variable
               This method can take 1-2 parameters. In the case of a single parameter, the fill method takes in a fillRule.
               The 2 possible options for the fillRule are 
                  1. nonzero : this is the defaulted value of the only required parameter of the fill method
                     The nonzero rule is used to determine if a point falls within an enclosed curve, and if so that point will be filled
                     https://en.wikipedia.org/wiki/Nonzero-rule
                  2. evenodd : this rule leaves certain shapes uncolored depending on their nested close paths to other shapes
                When using the nonzero rule, no parameters need to be specified, and you can simply execute the fill() method like so:  
  */      draw1.fill(); // this line turns the square purple because the drawing variable's fill style was set to purple.
  /*     the .fill method can be implemented with 2 parameters as well, the first being the region to fill, and the second parameter being the fillRule.
         we will look at implementing the fill method using 2 parameters later in the unit.
         
         Next, we will look at the .fillRect method:
         .fillRect(x, y, width, height) works extremely similarly to the basic rect(x, y, width, height) method in that it creates a rectangle based off of the given parameters,
         however the rectangle that the .fillRect() method creates will already be filled in with the color specified by the drawing variable's fillStyle when the rectangle is drawn onto the canvas by the stroke method.
         Lets see an example using a new canvas with a new fillStyle, and a new rectangle:
         (the canvas we are using now has the ID of 'rectangle')
  */
    let canvas2 = document.getElementById("rectangle");
    canvas2.height = 400;
    canvas2.width = 400;
    let draw2 = canvas2.getContext("2d");
    draw2.fillStyle = "teal";
    draw2.fillRect(10, 10, 100, 350);
    // as you can see, we have just drawn a teal rectangle!

  // This is the simplest method of drawing simple shapes like squares and rectangles, though it can be done in a more complex way, which we will see in future sections.
  // For now, we will continue covering drawing basic shapes. Next we will look at drawing a circle:

/*
  First we'll follow the steps we're exremely familiar with at this point to grab the canvas with the ID of 'circle',
  set its width and height, set the context to 2d, and then we can begin drawing!
*/
  let canvas3 = document.getElementById("circle");
  canvas3.height = 400;
  canvas3.width = 400; 
  let draw3 = canvas3.getContext("2d");
  draw3.fillStyle = "#B3EB13";
/* Now that we've got our canvas set up and ready to draw, we can take a look at the method of drawing a circle:
   To accomplish drawing a circle, we actually invoke a few different methods from the Canvas 2D API.
   The first of these methods is .beginPath()
   
   .beginPath() is called before beginning each line in a drawing, so that they can be drawn in a color indepented of the other lines in the drawing, if the programmer so desires.
   In this case, we will only be drawing one line, since a circle only consists of one connecting line. 
   However, we still invoke the beginPath() method to tell our canvas that we are beginning a new line.
   
   beginPath() documentation: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/beginPath
*/
  draw3.beginPath();
/* 
   After we invoke the beginPath() method, we invoke another new method, .arc()
   The .arc() method from the 2D Canvas API adds a circular arc to the current path.
   The method depends upon the provided parameters to draw a circle at the specified center starting point, with a specified radius, starting and ending angle, and a optional travel option.
   The method takes up to 6 parameters, which we will break down now: 
   
   .arc(x, y, radius, startAngle, endAngle, [, anticlockwise]);
   
        1. x: the first parameter provides the x-axis coordinate of the arc's center
        2. y: the second parameter provides the y-axis coordinate of the arc's center
          The first two parameters together (x,y) make up the center point of the circle.
        3. radius: the third parameter provides the radius of the circle, i.e. how wide the circle will be. This number must be positive.
        4. startAngle : the fourth parameter provides the angle at which the arc of the circle begins. This is measured clockwise from the positive x axis (think back to basic geometry when you learned the 4 quadrants of a Cartesian plane if the axes are confusing you)
                        this parameter is expressed in radians
        5. endAngle: the fifth parameter is the angle at which the arc of the circle ends, also expressed in radians and measured clockwise from the positive x axis
        6. anticlockwise: the sixth parameter is an optional boolean parameter, which when left unspeficied simply defaults to false. 
            If set to true, the arc will be drawn counterclockwise from the start to end angle,
            while setting the parameter to false, or simply not specifying a value for it at all, will cause the arc to be drawn clockwise.
            
        the .arc() method is not only used to draw circles; it can be used in any drawing to include an arc in any shape, but in this case we will invoke it to draw a circle:
*/
     // can you relate these parameters to their meanings? 
     // the circle will have a center point of (200, 200); that is it will have a center point of 200 on the x axis and 200 on the y.
        // because the circle canvas has a height and width of 400 pixels, we know that the point (200, 200) will be the dead center of the canvas. (not that a circle must always be drawn in the center of a canvas)
     // the circle has a radius of 100 pixels
     // To create a circle with the arc method, we follow this method for the start and end angles:
          // The starting angle of the arc is 0 radians, while the ending angle is 2 radians. Note that 2 is multiplied by Math.PI to transform it into radians.
     draw3.arc(200, 200, 100, 0, 2* Math.PI);
     // finally we invoke the stroke method and now we can see our circle on the third canvas! 
     draw3.stroke();
     // we can also fill the circle with a color using the fill() method, which will fill the current path with the current fillstyle, which we specified earlier to be a lime green hexadecimal color.
     draw3.fill();

/* Up until this point, we have covered how to draw 3 shapes in canvas : primitave shapes, and a circle.
   
   Canvas considers only one type of shape to be a primitive shape, and that is rectangles (which by default also includes squares)
   
   This means that the creation/drawing of this type of shape does not require us to create any new paths
   
   However, when we saw how to create a circle, we used the beginPath() method to create a new path to include our arc for the circle.
   
   Like the circle, all other shapes in canvas aside from rectangles and triangles must be drawn by creating and combining one or more paths.
   
   A path is simply a list of points that are connected by lines. The lines can be different in many ways, either by being of a different shape, color, width, curvature, etc.
   
   A path can be closed, though it does not have to be. 
   
   This allows for different path methods to be executed in between the method beginning the path, beginPath() and the closing of the path, closePath(). 
   
   These different path methods can be executed without closing the path, however, as long as the path was initiated with the beginPath() method. This method is mandatory. 
   
   The commands executed between the invokation of these two methods or after the beginPath() method is how we achieve the drawing of other types of shapes.
   
   Because this is more complex than what we have seen in this lesson, we will continue it in more depth in section 2.3 
   
   However, before concluding, we will first look at drawing a simple line. This may seem redundant and overly simple, but this is the foundation of drawing all other shapes in canvas, so it is important to grasp.
   
   First we will grab our canvas with the ID of 'line' and set it up as we have done before:
 
*/

    let canvas4 = document.getElementById("line");
    canvas4.height = 400;
    canvas4.width = 400;
    let draw4 = canvas4.getContext("2d");
    /* the first method we must invoke to begin drawing our line is .moveTo
      
        The .moveTo(x, y) method begins a new sub path at the point specified by the parameters of the method, x and y
        This is where the beginning of the drawing will start, so for now we will simply say we want our line to begin at coordinate (0,0):
  */
    draw4.moveTo(0, 0);
  /* The next method we invoke is the .lineTo() method.
  
      The .lineTo(x, y) method adds a straight line to the current sub-path, which we created by invoking the .moveTo method, 
      by connecting the last point of the sub-path, which in our case is (0,0), to the coordinate specified in the parameters of the .lineTo() method
      
      So lets say we want our line to stretch from coordinate (0,0) to coordinate (200, 75). We would achieve this like so:
  */
    draw4.lineTo(200, 75); 
    // however, we notice that our line does not appear on our canvas after invoking the lineTo method. 
    // This is because we have to invoke the stroke() method after we are done to draw our sub-path:
    draw4.stroke();

    // Now our line is drawn on our fourth canvas. Note that we began our line at coordinate (0,0), and the line begins at the top lefthand corner, meaning that the top left hand corner is cordinate (0,0).
    // In the next section, we will create more complex shapes using this method, such as a triangle, hexagon, pentagon, etc.

    /* Before the end of this lesson, we will also quickly cover how you can achieve text with canvas:
  
       Drawing text: the act of drawing text in canvas is relatively simple, and only requires 2 methods.
       Of course, we must set up our canvas as per usual:
    */
    let canvas5 = document.getElementById("words");
    canvas5.height = 400;
    canvas5.width = 400;
    let draw5 = canvas5.getContext("2d");
    // let's say we want to print the words "Bob Ross is da Boss" to our canvas.
    // first, similar to how we want to specify the fillStyle before using the fillRect() method, we want to specify a font for this canvas.
    // we do this by setting the .font variable of our draw5 variable to some value that follows the same syntax as the CSS font specifyer:
    draw5.font = "40px Copperplate";
    // the font style can be set to any CSS accepted/web safe font : https://www.cssfontstack.com/
    // you can also specify the styling of the font in this line, as you can see we specified the size of the font to be 40px here, but we could also specify "bold 40px Arial" or "italic 50px Futura"
    /* finally we invoke the fillText() method, which you may think colors the text, but this method actually 'fills' the canvas with the text you want to write:
       The .fillText(text, x, y, [,maxWidth]) method draws a text string at the specified coordinate (x,y) with an optional maximum width of the text
       the parameters are pretty straight forward:
       1. text : this is the text you want to be written onto the canvas.
       2. x: this is the x coordinate of where the string will be drawn
       3. y: this is the y coordinate of where the string will be drawn
       4. maxWidth: this parameter is optional and straightforward, it is the max width in pixels that the text may be once it is drawn onto the canvas
          if this parameter is left unspecified, the text is not confined to a specific width. 
    */
  draw5.fillText("Bob Ross is da Boss", 0, 300);
// or: 
  draw5.fillText("Bob Ross is da Boss", 0, 100, 270); //where 270 pixels is the maximum width of our text string.


///////////////////////// Exercises /////////////////////////
// 1. Create a canvas with the ID of "squares" with a height and width of 500 pixels
    // using Canvas, draw a red square that takes up the entirety of the canvas
    // next, draw an orange square within the red square that is 80% of the size of the original square. (Hint: if orange square is 500x500, 500*.8 = 400, the next will be 400x400)
        // center the orange square within the red square.
    // next, draw a yellow square within the orange square that is 75% of the size of the orange square.
        // center the yellow square within the orange square.
    // next, draw a green square within the yellow square that is 66% of the size of the yellow square.
        // center the green square within the yellow square.
    // next, draw a blue square within the green square that is 50% of the size of the green square.
        // center the blue square within the green square.
    // finally, draw a purple square within the blue square that is 50% of the size of the blue square.
        // center the purple square within the blue square.
    // at the end, you should have a rainbow of concentric squares, with purple on the very inner square and red on the outer square.

// 2. 
// 3. 
// 4. 
// 5. 
              
            
!
999px

Console