Book Image

Canvas Cookbook

Book Image

Canvas Cookbook

Overview of this book

With the growing popularity of HTML5 Canvas, this book offers tailored recipes to help you develop portable applications, presentations, and games. The recipes are simple yet creative and build on each other. At every step, the book inspires the reader to develop his/her own recipe. From basic to advanced, every aspect of Canvas API has been covered to guide readers to develop their own application, presentation, or game.
Table of Contents (16 chapters)
Canvas Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Drawing lines


The most basic shape in drawing is a line. Here you will see the various types of line that can be drawn. Also, you will see how different effects can be given to them.

This is the output of our first recipe:

How to do it...

This recipe is made by undertaking the following steps:

  1. Detect the canvas element.

  2. Write the initiating function to create the canvas and its context.

  3. Call the function to draw the line specified with different attributes.

The final code looks as follows:

<html>
<head>
  <title>Simple Lines</title>
    <script type="text/javascript">
      var can;
      var ctx;
      function init() {
        can = document.getElementById("MyCanvasArea");
        ctx = can.getContext("2d");
        drawLine(30,30,300,30,20,"orange","butt");//default cap style
        drawLine(30,80,300,80,20,"crimson","round");
        drawLine(30,130,300,130,20,"teal","square");
      }
      function drawLine(xstart,ystart,xend,yend,width,color,cap)
      {
        ctx.beginPath();
        ctx.strokeStyle=color;
        ctx.lineWidth=width
        ctx.lineCap=cap;
        ctx.moveTo(xstart,ystart);
        ctx.lineTo(xend,yend);
        ctx.stroke();
        ctx.closePath();
      }
    </script>
</head>
<body onload="init()">
<br/><br/>
  <center>
    <canvas id="MyCanvasArea"
width="320"
height="200"
style="border:3px solid brown;">
Your browser doesn't support canvas
    </canvas>
  </center>
</body>
</html>

How it works...

To set up the canvas you need the canvas element, which is embedded in the body tag of the code. The Canvas created will be of 320 x 200 and will have a brown colored border. The border color and the dimensions are specified through the properties of the canvas element. If your browser doesn't support canvas then it will display Your browser doesn't support canvas as mentioned in the canvas element of the HTML code.

The onload property is responsible for invoking the init() function to initialize the canvas and context as soon as you run the program:

<body onload="init()">
<canvas id="MyCanvasArea"
width="320"
height="200"
style="border:2px solid brown;">
</body>

The init() function, which is a part of <script> tag, has two parts:

  • Detecting the canvas

  • Calling the relevant functions

The following snippet shows how to do it:

      function init() {
        can = document.getElementById("MyCanvasArea");
        ctx = can.getContext("2d");
        drawLine(30,30,300,30,20,"orange","butt");  //default cap style
        drawLine(30,80,300,80,20,"crimson","round");
        drawLine(30,130,300,130,20,"teal","square");
      }

The purpose of the canvas API functions used in the preceding snippet are briefed here:

  • getElementById(): This function returns the element that has the ID attribute with the specified value. In our case the ID is MyCanvasArea. The function returns a null value if the ID doesn't exist. If there are two elements with the same ID then it returns the first element from the source code.

  • getContext(): This function returns a 2D drawing context on the canvas. It returns a null value if it is not supported by the browser.

The next part of init() calls the drawLine() function to draw a line on the canvas. The parameters/arguments passed to the function are the two coordinates of the line to be drawn, the width, the color, and the cap style.

The following is the function definition:

      function drawLine(xstart,ystart,xend,yend,width,color,cap)
      {
        ctx.beginPath();
        ctx.strokeStyle=color;
        ctx.lineWidth=width;
        ctx.lineCap=cap;
        ctx.moveTo(xstart,ystart);
        ctx.lineTo(xend,yend);
        ctx.stroke();
        ctx.closePath();
      }

The following functions of the canvas API are used in here:

  • beginPath(): Starts a new path by emptying the list of sub-paths. It resets the current path. This function can be called whenever new paths need to be created.

  • moveTo(x,y): Moves the starting point of the new sub-path to the (x,y) coordinates. This is like placing your pencil at a particular point from where you want to start drawing.

  • lineTo(x,y): Connects the last point in the sub-path to the (x,y) coordinates with a straight line. This function actually doesn't draw the line, it just connects it.

  • stroke(): Strokes the given path with the stroke style using the non-zero winding rule. This function actually draws the path.

  • closePath(): This is the function to end a path.

The following properties of the canvas API are used here:

  • strokeStyle: This defines the color in which the strokes are to be applied.

  • lineWidth: This defines the thickness of the line.

  • lineCap: This defines the cap style. There are three types, namely butt, round and square. The butt style is default. For round and square styles, extra length is added on both sides of the line. This is 1/2 of the width specified by you. You can see the difference in length of the first and last two lines shown in the output.

The cap style has an impact on the display. Notice the length of the first and the next two lines in the output. The next two lines have a longer length because of their cap styles.

The butt value means that no additional line cap is added.

The round value means that a semi-circle with the diameter equal to the lineWidth (in our example it is 20) is added on both sides.

The square value means that a rectangle of length the same as lineWidth and width the same as half of the lineWidth is added on both sides of the line.

The effects of butt and square look similar; however the lengths of lines differ.

You can create your own functions for common lines of code wherever you find it necessary. For example, the following two lines of code can be converted into a function that returns the canvas context:

can = document.getElementById("MyCanvasArea");
ctx = can.getContext("2d");

Also, depending on the return value of getContext(), you can detect whether your browser supports canvas.

There's more...

You can definitely try the following:

  • Comment the lines that call beginPath() and closePath()

  • Change the width and height of the canvas

  • Try changing the colors to green, yellow, pink, magenta, and so on

  • Call the drawLine() function with appropriate parameters to draw one more line