How to Use the HTML5 Canvas Element with JavaScript

Before HTML5 was introduced into the world of web developers, things were lifeless, unsatisfying, and complicated to achieve.

For instance, any developer who needed to create graphics and animations was forced to depend on tools like Flash plugin or Java plugin—something which was burdensome and head spinning.

Nikitka, who has more than seven years of web development experience and currently teaches people his skills, says that “the advent of the powerful HTML5 element called Canvas turned around things and empowered developers to complete actions that were previously difficult.”

What is HTML5 Canvas?

Canvas is an HTML5 element that allows you to easily and powerfully draw graphics, on the fly, using the ubiquitous JavaScript programming language.

The <canvas> element only works as a container for graphics; therefore, you should use JavaScript to render the graphics.

You can use the Canvas element to achieve various objectives on your web applications, including drawing graphs, creating HTML Canvas animations, developing games, or creating photos—all without depending on another external tool.

Amazingly, Canvas is available as an API, and it is supported by most modern browsers and platforms.

Furthermore, it’s cross-platform compatible. As such you can create an application once, and deploy it anywhere—on PCs or mobile devices.

Let’s see a Canvas markup code

Here is a simple markup for the HTML5 Canvas element:

<canvas width="320" height="160" id="canvasExample"></canvas>

As you can see on the above code, the Canvas element allows two specific attributes: width and height.

If you do not provide values for these two attributes, the Canvas will resort to its default values of 300 pixels for width and 150 pixels for height.

The id attribute is used for identifying the Canvas element in the JavaScript code.

Furthermore, you can include other CSS styling properties to make the canvas drawing region more interactive and visible, such as padding, background color, or border—just like with any other HTML element.

How to draw on a Canvas

To create graphics on a Canvas, you need to begin by targeting it using the Document Object Model (DOM).

And, an id attribute will assist you to identify the matching target location (in this HTML Canvas example, the id is “canvasExample”).

Initially, the <canvas> element is blank. Thus, to exhibit something, a JavaScript script should obtain the rendering context before drawing on it.

The Canvas element has an in-built DOM method referred to as getContext. It is a JavaScript function utilized in accessing the rendering context together with its drawing methods.

This function accepts a single parameter, which is usually the 2D graphics context (defined as “2d”).

Example of JavaScript Canvas Code

For example, to create a rectangle shape on the Canvas, you’ll need the following property and functions:

  • fillStyle = “colorit adds color to the shape; otherwise, it will have a default color of black
  • fillRect(x,y,width,height)—it draws a filled rectangle
  • strokeRect(x,y,width,height)—it gives the rectangle its outline
  • clearRect(x,y,width,height)—it clears the specified rectangular section and makes it entirely transparent

For defining coordinates, the Canvas grid or coordinate system is used. In this system, the original dimensions are located on the upper-left corner of the Canvas region, at coordinate (0,0).

As such, the X coordinate will be moving to the right whereas the Y coordinate will be moving downwards. The distance is in pixels.

Here is an image showing how the Canvas Grid system works:

Each of the above-mentioned functions for creating rectangles takes the following parameters for denoting the coordinates and dimensions:

  • x gives the horizontal position from the upper-left corner to the right
  • y gives the vertical position from the top-left corner to the bottom
  • width gives the width of the rectangle
  • height gives the height of the rectangle

Here is a JavaScript canvas tutorial example code that draws a rectangle:

<!DOCTYPE html>

<html>

<head>

<title>JavaScript HTML5 Canvas Example</title>

</head>

<body onload="canvasExample()">

<canvas width="320" height="160" id="canvasExample"></canvas>

<script>

function canvasExample(){

//identify the Canvas element via the DOM

var canvas = document.getElementById("canvasExample");

//checking for Canvas browser compatibility

if(canvas.getContext){

//Use getContext to specify the rendering context

var context = canvas.getContext('2d');

//setting of color

context.fillStyle = "blue";

//creating the rectangle

context.fillRect(50,50,150,250);

context.clearRect(75,75,100,50);

context.strokeRect(90,90,75,20);


}else{

//providing a fallback option

alert("Please a Canvas-Supporting Web Browser");

}

}

</script>

</body>

</html>

Here is the output on a browser:

This is what is happening in the JavaScript script:

  • The Canvas element is first identified through the DOM
  • The context is defined
  • The fillRect() function produces a rectangle of 150 by 250 pixels
  • The clearRect() function then deletes a rectangle of 100 by 50 pixels from the center
  • Lastly, strokeRect() function constructs a rectangle of 75 by 20 pixels within the cleared region

Wrapping up

As demonstrated by this HTML5 Canvas example, this element allows you to use JavaScript to dynamically render graphics on the web browser.

Canvas is great because it is completely open sourced, highly interactive, and very flexible. It’s what you need to add some life to your applications and accelerate their performance.

Therefore, you need to learn how it works and take your web development skills to the next level.

All the best.

Dr. Michael J. Garbade

I, Dr. Michael J. Garbade is the co-founder of the Education Ecosystem (aka LiveEdu), ex-Amazon, GE, Rebate Networks, Y-combinator. Python, Django, and DevOps Engineer. Serial Entrepreneur. Experienced in raising venture funding. I speak English and German as mother tongues. I have a Masters in Business Administration and Physics, and a Ph.D. in Venture Capital Financing. Currently, I am the Project Lead on the community project -Nationalcoronalvirus Hotline I write subject matter expert technical and business articles in leading blogs like Opensource.com, Dzone.com, Cybrary, Businessinsider, Entrepreneur.com, TechinAsia, Coindesk, and Cointelegraph. I am a frequent speaker and panelist at tech and blockchain conferences around the globe. I serve as a start-up mentor at Axel Springer Accelerator, NY Edtech Accelerator, Seedstars, and Learnlaunch Accelerator. I love hackathons and often serve as a technical judge on hackathon panels.

Recent Posts

Win Big with Our Amazon Fire Max 11 & AirPods Pro Giveaway!

We’re thrilled to announce an exciting opportunity for you to win not one but two…

1 month ago

Unleashing Potential: How Education Ecosystem Transforms Learning into Real-World Success

Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…

3 months ago

The Role of Artificial Intelligence in Modern Software Development

Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…

6 months ago

Highest Stable Coin Yields – (W16 – 2024)

Another week to bring you the top yield platforms for three of the most prominent…

7 months ago

LEDU Token OTC Trading

If you hold a large volume of LEDU tokens above 1 million units and wish…

8 months ago

Highest Stable Coin Yields – (W12 – 2024)

It’s another week and like always we have to explore the top yield platforms for…

8 months ago