The canvas is an HTML5 element used for graphics.
It was presented by Apple for their Mac OS in 2004. In 2005 it was introduced for other browsers.
The canvas is just a container, graphics is added through javascript in it.
Canvas is having height and width attributes.
Canvas element is used to draw graphs, animations, games and layout of photo.
Basic Syntax of Canvas:-
<canvas id="Canvas1" width="500" height="500">
<!-- Insert content here -->
</canvas>
Properties of <canvas> element:-
- Animation:- It allows different type of animations like bouncing, shadow, blinking etc.
- Flexible:- We can display shapes, images, lines, add video/audio etc with <canvas> element.
- Interactive:- It is not only for static graphics and images but also responds to the keyboard, mouse events.
- Browser Support:- Supported by all the browsers along with desktop, mobile and tablets.
- Available free development tools:- There are many free libraries available for advanced development.
We can draw many shapes using Canvas:-
1. Rectangle:- To draw a rectangle we need to give its x coordinate, y coordinate, width and height.
context.fillRect(x, y, width, height);
context.fillRect(40, 40, 100, 100); |
2. Lines:- Lines are just a path. To create a path first we have to begin it.
context.beginPath(); // Start the path
context.moveTo(20, 20); // Set the path origin
context.lineTo(340, 40); // Set the path destination
context.closePath(); // Close the path
context.stroke(); // Outline the path |
3. Circles:- We can draw circle using arc.
context.beginPath(); // Start the path
context.arc(230, 90, 50, 0, Math.PI*2, false); // Draw a circle
context.closePath(); // Close the path
context.fill(); // Fill the path |
Here is the example of HTML Canvas:-
HTML-
<body>
<canvas id="Canvas1" width="400" height="200"></canvas>
</body
JAVASCRIPT-
<script>
var canvas1 = document.getElementById("Canvas1"); //storing canvas element in a variable
var abc = canvas1.getContext('2d');
abc.shadowColor = "rgb(195, 195, 136)"; //this is the color of the shadow
abc.shadowOffsetX = 20; //position of shadow in x axis
abc.shadowOffsetY = 10; //position of shadow in y axis
abc.font = "50px arial"; //font size and font style
var gradient = abc.createLinearGradient(0, 0, 150, 100); //applying gradient effect on text
gradient.addColorStop(0, "rgb(102, 0, 0)"); // gradient starting color
gradient.addColorStop(1, "rgb(255, 153, 51)"); //gradient second color
abc.fillStyle = gradient;
abc.fillText("Canvas Graphics", 20, 60); //Text in which effect is applied
</script>
The output of the above code will be like this:-
0 Comment(s)