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

Canvas element: How to create graphic objects in HTML5

We will learn how canvas element in HTML5 provides a drawing surface that allows you to add text, shapes, and images to the websites dynamically.

Introduction

The graphic objects on a canvas are created by using the default stroke and fill color. However, you can use colors other than the default color for creating the graphic objects.

Below are the following properties can be used to apply colors on the canvas objects:

  • fillStyle
  • strokeStyle
  • shadowColor

fillStyle

The fillStyle property is used to define a color that will be used to fill any closed shape drawn on the canvas. The default value of the fillStyle property is solid black. The following syntax is used to apply fill style on a graphic object: fillStyle="color"; In the preceding syntax, you can specify the color as red, green, or blue. In addition, you can also specify the hexadecimal value of the color ranging from 000000 to FFFFFF.

Listing 1: Consider the following code for applying fill style on a rectangle drawn on the canvas having ID, myCanvas:

<!DOCTYPE HTML> 
<HTML> 
<HEAD>
<TITLE>Canvas element: How to create graphic objects in 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.strokeStyle="blue"; ctx.strokeRect(20,20,150,100); </SCRIPT> 
</BODY> 
</HTML> 	

The preceding code creates a rectangle of size 150 x 100 filled with red color at the position, (20, 20), on the canvas, as shown in the following figure.

A Rectangle Filled with the Red Color

Figure 1: A Rectangle Filled with the Red Color

strokeStyle

The strokeStyleproperty is used to set the outline color of a shape drawn on the canvas. The default value of the strokeStyleproperty is solid black. The following syntax can be used to apply stroke style on a graphic object: strokeStyle="color"; In the preceding syntax, colorspecifies the name or hexadecimal value of the color.

Listing 2: Consider the following code for applying the stroke style on a rectangle:

<!DOCTYPE HTML> 
<HTML> 
<HEAD>
<TITLE>Canvas element: How to create graphic objects in 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.strokeStyle="blue"; ctx.strokeRect(20,20,150,100); 
</SCRIPT> 
</BODY> 
</HTML> 
	

The preceding code will create a rectangle of size 150 x 100 with its outline colored in blue at the position, (20, 20), on the canvas, as shown in the following figure.

The Rectangle with Strokes Colored in Blue

Figure 2: The Rectangle with Strokes Colored in Blue

shadowColor

Once you have drawn a shape on the canvas, you may want to make it more stylish by casting a shadow on it. To cast a shadow of a graphic object on the canvas, you need to specify the color of the shadow. In addition, you need to specify how blurred you want your shadow to be. The shadowColorproperty is used to set the color for the shadows appearing on the graphic objects and the shadowBlurproperty is used to set the blur level for the shadows. You can use the following syntax to use the shadowColorproperty: shadowColor="color"; In the preceding syntax, colorspecifies the color that will be applied on shadows. The default value of the shadowColorproperty is solid black. You can use the following syntax to define the shadowBlur property: shadowBlur=number; In the preceding syntax, numberspecifies the blur level of the shadow. It can accept the integer values, such as 1, 2, and 20. Its default value is 0.

Listing 3: Consider the following code for applying shadows on a rectangle:

<!DOCTYPE HTML> 
<HTML> 
<HEAD>
<TITLE>Canvas element: How to create graphic objects in 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.shadowBlur=40; 
ctx.fillStyle="pink"; 
ctx.shadowColor="black"; 
ctx.fillRect(20,20,100,80); 
ctx.shadowColor="blue"; 
ctx.fillRect(140,20,100,80); 
</SCRIPT> 
</BODY> 
</HTML> 
	

In the preceding code, the blur level of the shadow of graphic objects is set to 40. In addition, the shadow color for the first rectangle is set to black and the shadow color for the second rectangle is set to blue. The output derived by using the shadowBlurand shadowColor properties is displayed in the following figure.

The Output Derived by Using the shadowBlur and shadowColor Properties

Figure 3: The Output Derived by Using the shadowBlur and shadowColor Properties

Working with Styles

Apart from creating simple shapes on the canvas, you can also apply styles, such as gradients, on them. A gradient is an object that provides smooth transition between two or more colors. To work with gradient styles, you can use the following methods:

  • addColorStop()
  • createLinearGradient()
  • createRadialGradient()
  • createPattern()

addColorStop()

To create gradients, you need to first specify the colors and their position in a gradient object. This is because the gradients are not visible until the colors are added to the objects. Therefore, to actually make the gradient effects visible on a graphic object, you need to add colors. You can add one or more colors on a gradient object by using the addColorStop()method. The addColorStop()method is used to specify the colors and their corresponding positions in a gradient object. The following syntax can be used to define the addColorStop()method: addColorStop(position,color); In the preceding syntax:

  • position: Specifies a value between 0.0 to 1.0 to represent the position from where to start and end the gradient color.
  • color: Specifies the color that needs to be applied on the respective position.

The addColorStop()method is used along with the createLinearGradient()or method to display the createRadialGradient() gradients.

createLinearGradient()

The createLinearGradient()method is used to return a gradient object that represents a linear gradient for painting the specified color along a line. The following syntax can be used to apply a linear gradient: createLinearGradient(x0,y0,x1,y1); In the preceding syntax:

  • x0: Specifies the x-coordinate of the start point of the gradient.
  • y0: Specifies the y-coordinate of the start point of the gradient.
  • x1: Specifies the x-coordinate of the end point of the gradient.
  • y1: Specifies the y-coordinate of the end point of the gradient. After creating the linear gradient object, you need to create the gradients by using the addColorStop()method.

Once you have created the linear gradient, you need to apply it on a graphic object by using the following ways:

Fill the graphic object with the linear gradient by using the fillStyleproperty. -Apply the linear gradient on the outline of the graphic object by using the strokeStyle property.

Listing 4: Consider the following code for applying a linear gradient on a rectangle:

<!DOCTYPE HTML> 
<HTML> 
<HEAD>
<TITLE>Canvas element: How to create graphic objects in 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"); 
var grad=ctx.createLinearGradient (0,0,170,0); 
grad.addColorStop(0,"blue"); 
grad.addColorStop("0.5","yellow"); 
grad.addColorStop(1,"red"); 
ctx.fillStyle=grad; 
ctx.fillRect(20,20,180,180); 
</SCRIPT> 
</BODY> 
</HTML> 
	

In the preceding code, a gradient object is created by using the createLinearGradient()method. Further, the addColorStop()method is used to specify different colors to the gradient object, and then, the gradient object is passed to the fillStyle property.

To shade the rectangle in three different colors from left to right. The output derived by using the createLinearGradient()method is displayed, as shown in the following figure.

The Output Derived by Using the createLinearGradient() Method

Figure 4: The Output Derived by Using the createLinearGradient() Method

createRadialGradient()

The createRadialGradient()method is used to return a gradient object that represents a radial or a circular gradient to be applied on a graphic object. A circular gradient paints colors along a cone specified by two circles, inner and outer. The following syntax can be used to apply a radial gradient: createRadialGradient (x0,y0,r0,x1,y1,r1); In the preceding syntax:

  • x0: Specifies the x-coordinate of the start point of the gradient.
  • y0: Specifies the y-coordinate of the start point of the gradient. (x0,y0) specifies the center coordinate of the first circle of the cone.
  • r0: Specifies the radius of the starting circle.
  • x1: Specifies the x-coordinate of the end point of the gradient.
  • y1: Specifies the y-coordinate of the end point of the gradient. (x1,y1) specifies the center coordinate of the second circle of the cone.
  • r1: Specifies the radius of the ending circle.

After creating the radial gradient object, you need to create the gradients by using the addColorStop()method. Once you have created the radial gradient, you need to apply it on a graphic object by using the following ways:

Fill the graphic object with the radial gradient by using the fillStyleproperty.

Apply the radial gradient on the outline of the graphic object by using the strokeStyle property.

Listing 5: Consider the following code snippet for applying a radial gradient on a rectangle:

<!DOCTYPE HTML> 
<HTML> 
<HEAD>
<TITLE>Canvas element: How to create graphic objects in 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"); 
var grad=ctx.createRadialGradient (75,50,5,90,60,100); 
grad.addColorStop(0,"blue"); 
grad.addColorStop("0.5","yellow"); 
grad.addColorStop(1,"red"); 
ctx.fillStyle=grad; 
ctx.fillRect(20,20,180,180); 
</SCRIPT> 
</BODY> 
</HTML> 
	

In the preceding code, a gradient object is created using the createRadialGradient()method. Further, the addColorStop()method is used to specify different colors to the gradient object and then, the gradient object is passed to the fillStyleproperty to shade the rectangle in three different colors along the radius given for the circle. The output derived by using the createRadialGradient()method is displayed in the following figure.

The Output Derived by Using the createRadialGradient() Method

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

createPattern()

The createPattern()method is used to create a pattern by displaying an image repeatedly on a canvas in the specified direction. For example, consider the following image.

The Image

Figure 6: The Image

If the preceding image is repeated vertically and horizontally, you can create a pattern, as shown in the following figure.

A Pattern

Figure 7: A Pattern

The following syntax can be used to create a pattern:

createPattern(img, "repeat|repeat-x| repeat-y|no-repeat"); 

In the preceding syntax:

  • img: Specifies the image or video to be used to create a pattern.
  • repeat: Specifies that the pattern should be repeated horizontally and vertically.
  • repeat-x: Specifies that the pattern should be repeated horizontally.
  • repeat-y: Specifies that the pattern should be repeated vertically.
  • no-repeat: Specifies that the pattern should be displayed only once.

Listing 6: Consider the following code snippet for repeating an image horizontally and vertically:

<!DOCTYPE HTML> 
<HTML> 
<HEAD>
<TITLE>Canvas element: How to create graphic objects in HTML5</TITLE>
</HEAD>
<BODY> 
<P>Image to use:</P> 
<IMG src="pattern.png" ID="pattern"> 
<P>Canvas:</P> 
<BUTTON onclick="draw ('repeat')">Repeat</BUTTON> 
<CANVAS ID="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag.</CANVAS> 
<SCRIPT> 
function draw(direction) { 
	var c=document.getElementById ("myCanvas"); 
	var ctx=c.getContext("2d");
	var img=document.getElementById ("pattern") 
	var pat=ctx.createPattern (img,direction); 
		ctx.rect(0,0,300,150); 
		ctx.fillStyle=pat; 
		ctx.fill(); 
} 
</SCRIPT> 

</BODY> 
</HTML> 
	

The preceding code snippet repeats the pattern.png image horizontally and vertically in the rectangular area on the canvas, when the user clicks the Repeat button, as shown in the following figure.

Repeat

Figure 8: Repeat

Conclusion

The canvas element in HTML provides a drawing surface that allows you to add text, shapes, and images to the websites dynamically.

See also



Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

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