The Talent500 Blog
HTML

Getting started with HTML Canvas

If you’ve ever visited a website with awesome 3D animations or highly interactive scenes in the background, chances are you’ve encountered the power of the HTML Canvas element.

Canvas allows you to create awesome 2D graphics on the web, and with the help of libraries like Three.js, it makes creating 3D animation on the web easy.

In this detailed blog, we will delve into HTML Canvas and its properties, and by the end of this blog, you will have solid knowledge about the HTML Canvas element.

So, let’s get started.

What is HTML Canvas? 

The HTML <canvas> element is a special kind of HTML tag that allows you to draw graphics, which you can manipulate with JavaScript. HTML Canvas is a two-dimensional grid and, unlike images or other formats that are defined using HTML and styled with CSS, the Canvas element is fully dynamic. You can create, animate, and modify graphics in real-time.

By default, the <canvas> will initially have a width of 300 pixels and a height of 150 pixels. Canvas also provides various methods for drawing paths, boxes, circles, and even rendering images.

Here is the syntax for initializing the canvas element:

    <canvas id=“myCanvas” width=“200” height=“100”></canvas>    

Here, id is used to identify the canvas element, and width and height attributes define the size of the canvas.

To draw on the canvas, you need to access it in your JavaScript code. You can do this by targeting the element by its ID.

 var canvas = document.getElementById(“myCanvas”);

  var ctx = canvas.getContext(“2d”);

The getContext(‘2d’) method is used to obtain the rendering context and its drawing functions. ctx is now the object that directly represents the drawing area of the canvas and allows us to draw 2D shapes.

How to Draw basic shapes using HTML Canvas

Drawing basic shapes using HTML Canvas is straightforward and involves using JavaScript to manipulate the Canvas element. In this section we will look at some examples for drawing some fundamental shapes like rectangles, circles, and lines.

The main method for drawing a path is enclosed within the beginPath() and closePath() method.

  • beginPath():  The beginPath() property starts a new path by emptying the list of sub-paths.
  • closePath(): The closePath() property adds a straight line to the path, going to the start of the current sub-path.

Drawing a Rectangle

Rectangles are among the easiest shapes to draw on the canvas. You can use the fillRect() method to create a rectangle on the canvas.

The following code shows how to draw a rectangle on the canvas:

ctx.fillStyle = ‘blue’; // Set color

ctx.fillRect(20, 20, 150, 100); // Draw a rectangle (x, y, width, height)

Getting started with HTML Canvas 1

Here the main functions are:

  • fillRect(x, y, width, height): The fillRect method draws a filled rectangle.
  • strokeRect(x, y, width, height): The strokeRect method draws a rectangular outline.
  • clearRect(x, y, width, height): Clears the specified rectangular area, making it fully transparent.

Drawing Circles (Arcs)

To draw circles, you use the arc() method by specifying its center, radius, and angles. Circles are just arcs making a complete turn.

The following code shows how to draw a circle on the canvas

 <script>

      var canvas = document.getElementById(“myCanvas”);

      var ctx = canvas.getContext(“2d”);

      ctx.beginPath(); // Start a new path

      ctx.arc(100, 200, 50, 0, Math.PI * 2); // Draw a circle (centerX, centerY, radius, startAngle, endAngle)

      ctx.fillStyle = “red”;

      ctx.fill();

      ctx.closePath();

    </script>

Getting started with HTML Canvas 2

The main methods for drawing a circle are:

  • arc(x, y, radius, startAngle, endAngle, anticlockwise): The arc() method is used to  draw an arc/curve.
  • arcTo(x1, y1, x2, y2, radius): The arcTo method is used to create an arc/curve between two tangents.

Drawing Lines

Drawing a line involves moving a path to a starting point and then drawing a line to a new position.

The following code shows how to draw a Line in the canvas:

<script>

      var canvas = document.getElementById(“myCanvas”);

      var ctx = canvas.getContext(“2d”);

      ctx.beginPath(); // Start a new path

      ctx.moveTo(100, 150); // Move the path to the start point

      ctx.lineTo(450, 250); // Draw a line to (x, y)

      ctx.strokeStyle = “black”;

      ctx.stroke();

      ctx.closePath();

    </script>

Getting started with HTML Canvas 3

The main methods for drawing lines are 

  • moveTo(x, y):  The moveTo() property moves the pen to the specified coordinates without creating a line.
  • lineTo(x, y): The lineTo() method draws a line from the current drawing position to the specified x and y coordinates.
  • stroke():The stroke() method strokes the current sub-paths with the current stroke style.
  • fill(): The fill() method Fills the current sub-paths with the current fill style.

We can combine these to draw any kind of figure. For example, if you want to draw a triangle, this is how you do it:

    <script>

      var canvas = document.getElementById(“myCanvas”);

      var ctx = canvas.getContext(“2d”);

      ctx.beginPath();

      ctx.fillStyle = “red”;

      ctx.moveTo(75, 50);

      ctx.lineTo(200, 150);

      ctx.lineTo(200, 50);

      ctx.fill();

      ctx.closePath();

    </script>

Getting started with HTML Canvas 4

Drawing Text on HTML Canvas

Text rendering on HTML Canvas is a feature, allowing developers to add textual content directly onto their graphics.

Canvas provides two main methods for drawing text: fillText() for filled text and strokeText() for outlined text. These methods offer flexibility in how text is displayed on the canvas.

  • fillText(text, x, y [, maxWidth]): The fillText() is used to draw text filled with a solid color.
  • strokeText(text, x, y [, maxWidth]): The strokeText() creates text with an outline, useful for adding emphasis or style.

Using both methods together can create visually appealing and easily readable text. For instance, a white filled text with a black outline ensures readability against varying backgrounds.

    <script>

      var canvas = document.getElementById(“myCanvas”);

      var ctx = canvas.getContext(“2d”);

      ctx.font = “70px Sans”;

      ctx.fillStyle = “red”;

      ctx.strokeStyle = “black”;

      ctx.lineWidth = 5;

      ctx.fillText(“Hello Canvas!”, 50, 100);

      ctx.strokeText(“Hello Canvas!”, 50, 300);

      ctx.closePath();

    </script>

Getting started with HTML Canvas 5

Drawing Images on HTML Canvas

The drawImage()  method can be used to render entire images, scale them, or draw specific portions.

To add images to a canvas, you just need to follow two simple steps. First, find an image you want to use. This can be an image element on your webpage (HTMLImageElement), another canvas element, or even an image from a URL.

Then, use the drawImage() function to put the image onto your canvas.

Syntax:

 drawImage(image, x, y, width, height)

Here is an example

 <script>

      var canvas = document.getElementById(“myCanvas”);

      var ctx = canvas.getContext(“2d”);

      var img = new Image();

      img.onload = function () {

        ctx.drawImage(img, 50, 50, 200, 200);

      };

      img.src = “https://images.pexels.com/photos/881613/pexels-photo-881613.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500”;

      ctx.closePath();

    </script>

Getting started with HTML Canvas 6

Basic Animations using HTML Canvas 

Animations are the best way to catch user attention and HTML Canvas allows for the creation of intricate animations. 

At the heart of canvas animation is the animation loop, a cycle of drawing and redrawing content at regular intervals. The requestAnimationFrame() is used for updating your elements on the Canvas for the next repaint.

Here is a simple example, where we create a bouncing animation using HTML Canvas.

<!DOCTYPE html>

<html lang=“en”>

  <head>

    <meta charset=“UTF-8” />

    <meta name=“viewport” content=“width=device-width, initial-scale=1.0” />

    <title>Canvas Animation</title>

    <style>

        canvas{

            background-color: rgb(15, 14, 14);

        }

    </style>

  </head>

  <body>

    <canvas id=“myCanvas” width=“1024” height=“800”></canvas>

    <script>

      var canvas = document.getElementById(“myCanvas”);

      var ctx = canvas.getContext(“2d”);

      var x = canvas.width / 2;

      var y = canvas.height 30;

      ctx.fillStyle=“black”;

      var dx = 2;

      var dy = 2;

      var ballRadius = 25;

      function drawBall() {

        ctx.beginPath();

        ctx.arc(x, y, ballRadius, 0, Math.PI * 2);

        ctx.fillStyle = “#0095DD”;

        ctx.fill();

        ctx.closePath();

      }

      function animate() {

        requestAnimationFrame(animate);

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        drawBall();

        if (x + dx > canvas.width ballRadius || x + dx < ballRadius) {

          dx = dx;

        }

        if (y + dy > canvas.height ballRadius || y + dy < ballRadius) {

          dy = dy;

        }

        x += dx;

        y += dy;

      }

      animate();

    </script>

  </body>

</html>

Getting started with HTML Canvas 7

Codepen: https://codepen.io/adarsh-gupta101/pen/wvOzeoR 

Adding Interactivity to Canvas Animations

Interactivity is essential in modern websites, and HTML Canvas offers a great way to achieve this. It allows you to create animations that react to user actions like mouse movements. By using event listeners, you can make your website more engaging, giving users the ability to interact with your content in real-time.

Let’s take an example and see it in action

  <body>

    <canvas id=“myCanvas” width=“1024” height=“800”></canvas>

    <script>

      document.addEventListener(“DOMContentLoaded”, function () {

        const canvas = document.getElementById(“myCanvas”);

        const ctx = canvas.getContext(“2d”);

        let width = (canvas.width = window.innerWidth);

        let height = (canvas.height = window.innerHeight);

        const trailingElements = [];

        window.addEventListener(“resize”, function () {

          width = canvas.width = window.innerWidth;

          height = canvas.height = window.innerHeight;

        });

        let lastMouseX = 0;

        let lastMouseY = 0;

        let mouseVelocityX = 0;

        let mouseVelocityY = 0;

        function addConfettoAndTrail(e) {

          mouseVelocityX = e.clientX lastMouseX;

          mouseVelocityY = e.clientY lastMouseY;

          lastMouseX = e.clientX;

          lastMouseY = e.clientY;

          let randomOffsetX = (Math.random() 0.5) * 100;

          let randomOffsetY = (Math.random() 0.5) * 100;

          const trail = document.createElement(“div”);

          trail.classList.add(“trail”);

          trail.style.top = e.clientY + “px”;

          trail.style.left = e.clientX + “px”;

          document.body.appendChild(trail);

          const trailingElements = [];

          trailingElements.push(trail);

          if (trailingElements.length > 14) {

            const removedTrail = trailingElements.shift();

            removedTrail.remove();

          }

        }

        canvas.addEventListener(“mousemove”, addConfettoAndTrail);

        let lastTime = 0;

        function update(time = 0) {

          const deltaTime = time lastTime;

          lastTime = time;

          requestAnimationFrame(update);

        }

        update();

      });

    </script>

  </body>

Getting started with HTML Canvas 8

Codepen: https://codepen.io/adarsh-gupta101/pen/rNRMxyJ 

Like this, you can create various Interactive animations using the Canvas element and it opens up a door for creativity.

Conclusion

In this detailed blog on HTML Canvas, we have learned various things about the Canvas element, including how to draw a line, circle and other shapes. We even explored various animations, such as an interactive mouse animation. This blog is a good start if you are new to HTML canvas. 

Keep Learning!

0
Adarsh M

Adarsh M

A soon-to-be engineer and software developer. Curious about advanced tools and Web technologies. Loves to be a part of fast moving technical world.

Add comment