Definition:
The canvas is an HTML non-empty element that is used to draw graphics on web pages. The HTML <canvas> gives you an easy and powerful way to draw graphics using JavaScript.
HTML Canvas Example
<canvas id="myCanvas" width="200" height="200"></canvas>
The width and height attribute is necessary to define the size of the canvas.
The <canvas> element must have an id attribute so it can be referred to by JavaScript.
By default, the <canvas> element has no border and no content we can add a border and other styles using CSS.
How to draw the canvas With JavaScript.
Note:- The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics.
Step 1: Define the canvas by using <canvas> element.
<canvas id="myCanvas" width="200" height="200" style="border:solid"></canvas>
Step 2: Find the Canvas Element by using the HTML DOM method getElementById():
var canvas = document.getElementById("myCanvas");
Step 3: Create a Drawing Object
The getContext() is a predefined HTML object, with properties and methods for drawing:
var obj = canvas.getContext("2d");
Step 4: Set the fill style of the drawing object.
In my example we fill the style of the drawing object to the color blue:
obj.fillStyle = "blue";
The fillStyle property can be a CSS color, a gradient, or a pattern. The default fillStyle is black.
Overall code:
<!DOCTYPE html> <head> <title>HTML Camvas</title> </head> <body> <canvas id="myCanvas" width="200" height="200" style="border: solid;"></canvas> <script> var canvas = document.getElementById("myCanvas"); var obj = canvas.getContext("2d"); obj.fillStyle = "blue"; obj.fillRect(0,0,200,200); </script> </body> </html>
In the above code, we used the fillRect(x, y, width, height) method to draw a rectangle, filled with the fill style, on the canvas.
-:Output:-

If you need custom WordPress Development services then feel free to reach us.
!!Have a Great Day Ahead!!
Be the first to comment.