HTML Canvas - First Application



In the previous chapters we have already seen how to create a Canvas element using the <canvas> tag. Now we will style the Canvas element using simple CSS styles which helps us to understand how the Canvas element is formed.

Let us first create an empty Canvas element and style using the following attributes

  • Add background-color

  • Change border

Adding background color to the Canvas element

Following code demonstrates how to add color to the Canvas element using CSS style attributes. We are using background_color attribute of the Canvas element. The code is given below.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Canvas Element</title>
   <style>
      #canvas{
         border:5px solid black;
         background-color: green;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="150" >
      This text is displayed if your browser does not support HTML5 Canvas or if JavaScript is disabled.
   </canvas>
</body>
</html>

Output

Adding Background Color

Changing border of the Canvas element

By using CSS style attributes, we can change the border style of Canvas element easily. It is useful when creating an interactive visual graphics using Canvas. Following is the implementation of changing the border style of the Canvas element.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Canvas Element</title>
   <style>
      #canvas{
         border:2px dotted black;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="150" >
      This text is displayed if your browser does not support HTML5 Canvas or if JavaScript is disabled.
   </canvas>
</body>
</html>

Output

Changing Border

Instead of using solid while creating the Canvas element, we can use one of the following to change the style of the Canvas border per our requirement

  • Dotted

  • Dashed

  • Double

  • Groove

  • Ridge

Advertisements