The Talent500 Blog

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.

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)

Here the main functions are:

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>

The main methods for drawing a circle are:

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>

The main methods for drawing lines are 

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>

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.

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>

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>

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>

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>

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