3 Simple Steps to Draw HTML Canvas
This blog will help you to learn about HTML canvas drawing in 3 simple steps.
Drawing HTML canvas
HTML canvas has various methods for drawing paths, circles, boxes, shapes, texts, adding
images. The HTML
<canvas> has only a container of graphics that can be used to draw the graphics that can be done by scripting (
JavaScript).
The following are the three simple steps you need to draw the HTML canvas.
Step 1: Finding the canvas element
The first thing you have to do is that, find the canvas element using the HTML DOM (Document Object Model: root node of HTML document) method getElementById().
The getElementById() method returns the element that has an ID attribute with the specified value.
Syntax
- var canvas=document.getElementById(“newCanvas”) ;
Here ID is “newCanvas” and canvas is a variable name.
Step 2: Creating a drawing object
Now, you need a drawing object for the canvas. The getContext() method used to returns an object that provides methods and properties for drawing on the canvas.
Syntax
- var context=canvas.getContext(“2d”);
Step 3: Drawing on the canvas
Now, in the final step, you can draw what you want on the canvas by setting the fill style of the drawing object to the various colors. The
fillStyle is a property that can be a CSS color, a
gradient, or a pattern and the default color for fillStyle is black. The
fillRect(x, y, width, height) is a method used to draw a rectangle filled with fillStyle on the canvas.
Syntax
- Context.fillStyle=”green”;
- Context.fillRect(0,0,150,20)
Samples of canvas drawing with JavaScript:
You can draw paths, circles, boxes, shapes, texts, adding images, etc. on the canvas.
- <html>
- <body>
- <canvas id="newCanvas" width="200" height="100" style="border:1px solid green;"></canvas>
- <script>
- var canvas = document.getElementById("newCanvas");
- var context = canvas.getContext("2d");
- context.fillStyle = "lightgreen";
- context.fillRect(10,10,180,100);
- </script>
- </body>
- </html>
Output:
Similarly, you can draw these also by applying other canvas methods.
Thank you, keep learning and sharing.