- HTML Canvas Tutorial
- HTML Canvas - Home
- HTML Canvas - Introduction
- Environmental Setup
- HTML Canvas - First Application
- HTML Canvas - Drawing 2D Shapes
- HTML Canvas - Path Elements
- 2D Shapes Using Path Elements
- HTML Canvas - Colors
- HTML Canvas - Adding Styles
- HTML Canvas - Adding Text
- HTML Canvas - Adding Images
- HTML Canvas - Canvas Clock
- HTML Canvas - Transformations
- Composting and Clipping
- HTML Canvas - Basic Animations
- Advanced Animations
- HTML Canvas API Functions
- HTML Canvas - Element
- HTML Canvas - Rectangles
- HTML Canvas - Lines
- HTML Canvas - Paths
- HTML Canvas - Text
- HTML Canvas - Colors and Styles
- HTML Canvas - Images
- HTML Canvas - Shadows and Transformations
- HTML Canvas Useful Resources
- HTML Canvas - Quick Guide
- HTML Canvas - Useful Resources
- HTML Canvas - Discussion
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
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
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