Back to Top

Basic Of HTML Canvas

Updated 6 June 2024


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.

Searching for an experienced
WordPress Company ?
Find out More

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>
    <title>HTML Camvas</title>
    <canvas id="myCanvas" width="200" height="200" style="border: solid;"></canvas>
        var canvas = document.getElementById("myCanvas");
        var obj = canvas.getContext("2d");
        obj.fillStyle = "blue";

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.



If you need custom WordPress Development services or WordPress Theme Development Service then feel free to reach us.

!!Have a Great Day Ahead!!

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home