Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Creating Canvas elements using HTML5

In this article we will learn how to work and create canvas elements in HTML5.

You often need to add graphics, such as bitmap images or 2D shapes, on the pages of your website. In addition, you can add text and apply different colors and gradients to the graphics being added to the Web pages.

Introducing Canvas

LearnGraphs ltd. offers online tutorials on basic graphing skills. These tutorials include a wide variety of graphs, such as bar graph, histogram, and pie chart, which need to be drawn on their Web pages. However, to draw graphs on a Web page, you need to incorporate shapes, such as lines, arcs, circles, and apply effects, such as colors and gradients, on the shapes. With the introduction of canvas element in HTML, you can create such graphics and apply animations on a Web page easily. The canvas element has a huge set of functions in the form of a 2D Application Programming Interface (API) that are used to draw graphics on the canvas.

Creating a Canvas

Canvas provides an easy and powerful way to create graphics on a Web page. A canvas has no content of its own. A canvas is simply an area on a Web page that acts as a container for embedding graphic objects. It allows dynamic rendering of bitmap images and 2D shapes by using JavaScript. You need to perform the following tasks to create a canvas and use it for drawing a variety of graphics:

  • Define the Canvas
  • Access the Canvas

Defining the Canvas

A canvas is defined by using the tag. This tag is defined in the body section of the HTML document. The tag provides various attributes that enable you to specify the size, border, and ID for the canvas. The attributes provided by the tag are listed in the following table.

Listing 1: We can define a canvas by using the following code within the <BODY> tag:

<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black"> </CANVAS>

The preceding code will create a canvas with ID, myCanvas, of size 300 x 300 with a solid black border of 1pxthickness.

Accessing the Canvas

Defining a canvas element only creates a blank drawing surface. However, to actually draw graphic objects on the canvas, you need to access the canvas in JavaScript code.

Listing 2: We can write the following code in the tag to access the canvas element:

<SCRIPT> var c=document.getElementById ("myCanvas"); var ctx=c.getContext("2d"); </SCRIPT> 

In the preceding code, the getElementById()method is used to return the reference of the element with ID,myCanvas, and stores the reference in the variable named c. Further, the getContext()method is used to return a drawing context object that provides the methods and properties needed for drawing graphics on the canvas. This object is stored inside the variable named ctx. The getContext()method accepts a string argument that specifies the type of canvas to be created. In the preceding code, 2dis passed as an argument to the getContext()method as majority of the browsers support the creation of 2D graphics inside the canvas.

Working with Color, Shapes, and Styles

Consider a scenario of a website for Preschoolers, which provides basic learning solutions to kids. It provides simple online activities that assist kids to identify basic colors and shapes. For example, one of the activities displays a color picker and various shapes to the students. The students are asked to identify and fill a particular shape with the specified color as a part of this activity. To create such applications, you need to embed color, shapes, and styles on a Web page. Using canvas, this can be achieved by using the JavaScript predefined color and style properties and methods. The introduction of Canvas has simplified the task of drawing objects, such as rectangles, on a Web page. You can easily draw these objects by using the JavaScript methods. Further, you can also specify the colors, gradients, or pattern styles to decorate the graphic objects on the canvas.

Working with Shapes

After creating a canvas, you can draw shapes, such as rectangle and square, on it. Rectangles and squares are the easiest shapes to draw on the canvas element by using the JavaScript functions. Using these functions, you can create a shape, clear a certain portion of the shape, and apply outline to the shape. For this, you can use the following methods:

  • rect()
  • fillRect()
  • strokeRect()
  • clearRect()

rect():

The rect()method is used to create a rectangle on the canvas. However, it picks the default color of the canvas to draw the outline of the rectangle. Therefore, the rectangle is not visible on the canvas. To make a rectangle visible on the canvas, you need to provide its outline or stroke color by using the stroke()method. This method uses the default black stroke to draw the rectangle. The syntax of using the rect()method to create a rectangle on a canvas is: rect(x,y,width,height); In the preceding syntax:

  • x: Specifies the x-coordinate of the upper-left corner of the rectangle.
  • y: Specifies the y-coordinate of the upper-left corner of the rectangle.
  • width: Specifies the width of the rectangle, in pixels.
  • height: Specifies the height of the rectangle, in pixels. The following figure explains the dimensions of a rectangle.
The Dimensions of a Rectangle

Figure 1: The Dimensions of a Rectangle

Listing 3: Consider the following code snippet for creating a rectangle on the canvas having ID, myCanvas:

<!DOCTYPE HTML> 
<HTML>
<head>
<title>Canvas Element HTML5</title>
</head>
 <BODY> 
<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black"> </CANVAS>
 <SCRIPT> var c=document.getElementById ("myCanvas"); var ctx=c.getContext("2d"); ctx.rect(30,40,120,120); ctx.stroke(); 
</SCRIPT> 
</BODY>
 </HTML> 

The preceding code snippet creates a rectangle of size 120 x 120 starting from the coordinates, (30, 40), on the canvas, as shown in the following figure.

The Rectangle Created on the Canvas

Figure 2: The Rectangle Created on the Canvas

fillRect()

The fillRect()method is used to create a rectangle filled with the specified color. The default fill color is black. The following syntax is used to create a filled rectangle on a canvas: fillRect(x,y,width,height);

Listing 4: Consider the following code for creating a filled rectangle on the canvas:

<HTML>
<head>
<title>Canvas Element HTML5</title>
</head>
 <BODY> 
<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black"> </CANVAS> 
<SCRIPT>
var c=document.getElementById ("myCanvas"); var ctx=c.getContext("2d"); ctx.fillRect(30,40,120,120); </SCRIPT> 
</BODY>
 </HTML> 

The preceding code will create a rectangle filled with black color, as shown in the following figure.

A Rectangle Filled with Black Color

Figure 3: A Rectangle Filled with Black Color

strokeRect()

When you create a rectangle using by the rect()method, you also need to use the stroke()method to define its outline on the canvas. Instead of using two methods, rect()and stroke(), to draw a rectangle on the canvas, you can use a single method, strokeRect(), to draw a rectangle with the specified stroke color. By default, the strokeRect()method uses the black color to create an outline of the rectangle. The syntax of using the strokeRect()method to draw a rectangle on a canvas is: strokeRect(x,y,width,height);

Listing 5: Consider the following code for drawing a rectangle on a canvas:

<HTML>
<head>
<title>Canvas Element HTML5</title>
</head>
 <BODY> 

<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black"> </CANVAS> 
<SCRIPT>
var c=document.getElementById ("myCanvas"); var ctx=c.getContext("2d"); ctx.strokeRect(30,40,120,120); 
</SCRIPT> 
</BODY> 
</HTML> 

The preceding code will create a rectangle of size 120 x 120 at the position, (30, 40), on the canvas, as shown in the following figure.

The Rectangle Created by Using the strokeRect() Method

Figure 4: The Rectangle Created by Using the strokeRect() Method

clearRect()

The clearRect()method is used to clear a portion of the rectangle. It clears the specified pixels within the given rectangle. The following syntax can be used to clear a rectangle on a canvas: clearRect(x,y,width,height);

Listing 6: Consider the following code to clear a part of the rectangle created on the canvas having ID, myCanvas:

<HTML>
<head>
<title>Canvas Element HTML5</title>
</head>
 <BODY> 
<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black"> </CANVAS> 

<SCRIPT> var c=document.getElementById ("myCanvas"); var ctx=c.getContext("2d"); ctx.fillRect(30,40,120,120); ctx.clearRect(50,60,40,40);
</SCRIPT> 
</BODY>
 </HTML> 

The preceding code clears a portion of the rectangle of size 40 x 40 starting from the coordinates, (50, 60), as shown in the following figure.

The Output Derived by Using the clearRect()Method

Figure 5: The Output Derived by Using the clearRect()Method

Listing 7: Consider the following code to draw rectangular shapes on the canvas using various methods:

<HTML>
<head>
<title>Canvas Element HTML5</title>
</head>
 <BODY> 
<CANVAS ID="myCanvas" width="600" height="300" style="border:1px solid black"></CANVAS> 
<SCRIPT> var c=document.getElementById ("myCanvas"); var ctx=c.getContext("2d"); ctx.rect(30,40,120,120); ctx.stroke(); ctx.fillRect(160,40,120,120); ctx.stroke(); ctx.strokeRect(300,40,120,120); ctx.fillRect(460,40,120,120); ctx.clearRect(500,60,40,40); </SCRIPT>

 </BODY>
 </HTML>

The preceding code creates rectangles on the canvas, as shown in the following figure.

The Rectangles Created on the Canvas

Figure 6: The Rectangles Created on the Canvas

Conclusion

The canvas element in HTML 5 provides a drawing surface that allows you to add text, shapes, and images to the websites dynamically, even you can apply jquery also.

Hope you liked, see you next time.

See also:



Working in Software Development domain from 7 years now and is well equipped with programming languages like HTML, CSS, Java, PHP, .NET etc.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login