5 HTML5 Canvas Examples

Introduction to HTML5 Canvas

The HTML5 Canvas element is a powerful tool for creating dynamic, interactive, and graphical content on the web. It allows developers to draw graphics, manipulate images, and create animations using JavaScript. The Canvas element is a rectangular area where graphics can be drawn, and it can be used to create a wide range of applications, from simple drawings to complex games.

Example 1: Basic Drawing

To get started with the HTML5 Canvas, we can create a basic drawing example. This example will demonstrate how to create a canvas element, get a reference to the 2D drawing context, and draw a simple shape.
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  ctx.fillStyle = 'red';
  ctx.fillRect(10, 10, 50, 50);
</script>

This code creates a canvas element with an ID of “myCanvas” and a size of 400x200 pixels. It then gets a reference to the 2D drawing context using the getContext() method and sets the fill style to red. Finally, it draws a rectangle at position (10, 10) with a size of 50x50 pixels using the fillRect() method.

Example 2: Animations

The HTML5 Canvas can also be used to create animations. This example will demonstrate how to create a simple animation by drawing a circle that moves across the canvas.
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  var x = 10;
  var y = 10;
  var radius = 20;
  function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, 2 * Math.PI);
    ctx.fillStyle = 'blue';
    ctx.fill();
    x += 2;
    if (x > canvas.width) {
      x = 0;
    }
    requestAnimationFrame(animate);
  }
  animate();
</script>

This code creates a canvas element and gets a reference to the 2D drawing context. It then defines the initial position, radius, and fill style of the circle. The animate() function is called repeatedly using the requestAnimationFrame() method, which clears the canvas, draws the circle at the current position, and updates the position for the next frame.

Example 3: Image Manipulation

The HTML5 Canvas can also be used to manipulate images. This example will demonstrate how to load an image, draw it on the canvas, and apply a simple filter to it.
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  var img = new Image();
  img.src = 'image.jpg';
  img.onload = function() {
    ctx.drawImage(img, 0, 0);
    var pixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
    for (var i = 0; i < pixels.data.length; i += 4) {
      pixels.data[i] = pixels.data[i] + 100; // increase red channel
    }
    ctx.putImageData(pixels, 0, 0);
  };
</script>

This code creates a canvas element and gets a reference to the 2D drawing context. It then loads an image using the Image() constructor and sets the onload event handler to draw the image on the canvas and apply a simple filter to it. The filter increases the red channel of each pixel by 100.

Example 4: Interactive Graphics

The HTML5 Canvas can also be used to create interactive graphics. This example will demonstrate how to create a simple drawing application that allows users to draw on the canvas using their mouse.
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  var drawing = false;
  canvas.addEventListener('mousedown', function(e) {
    drawing = true;
    var x = e.clientX - canvas.offsetLeft;
    var y = e.clientY - canvas.offsetTop;
    ctx.beginPath();
    ctx.moveTo(x, y);
  });
  canvas.addEventListener('mousemove', function(e) {
    if (drawing) {
      var x = e.clientX - canvas.offsetLeft;
      var y = e.clientY - canvas.offsetTop;
      ctx.lineTo(x, y);
      ctx.stroke();
    }
  });
  canvas.addEventListener('mouseup', function() {
    drawing = false;
  });
</script>

This code creates a canvas element and gets a reference to the 2D drawing context. It then sets up event listeners for the mousedown, mousemove, and mouseup events to handle user input. When the user clicks and drags on the canvas, the application draws a line on the canvas.

Example 5: Game Development

The HTML5 Canvas can also be used to create games. This example will demonstrate how to create a simple game of Pong using the Canvas element.
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  var ball = { x: 10, y: 10, radius: 10, velocityX: 2, velocityY: 2 };
  var paddle = { x: 10, y: 10, width: 10, height: 100 };
  function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI);
    ctx.fillStyle = 'white';
    ctx.fill();
    ball.x += ball.velocityX;
    ball.y += ball.velocityY;
    if (ball.x > canvas.width || ball.x < 0) {
      ball.velocityX = -ball.velocityX;
    }
    if (ball.y > canvas.height || ball.y < 0) {
      ball.velocityY = -ball.velocityY;
    }
    ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
    requestAnimationFrame(animate);
  }
  animate();
</script>

This code creates a canvas element and gets a reference to the 2D drawing context. It then defines the initial position, radius, and velocity of the ball, as well as the position and size of the paddle. The animate() function is called repeatedly using the requestAnimationFrame() method, which clears the canvas, draws the ball and paddle, and updates the position of the ball for the next frame.

💡 Note: These examples demonstrate the basics of using the HTML5 Canvas element, but there are many more advanced techniques and features available, such as using WebGL for 3D graphics, using the `canvas` element in combination with other HTML elements, and optimizing performance for complex graphics and animations.

To summarize, the HTML5 Canvas element is a powerful tool for creating dynamic, interactive, and graphical content on the web. It can be used to create a wide range of applications, from simple drawings to complex games, and is an essential part of any web developer’s toolkit.

What is the HTML5 Canvas element?

+

The HTML5 Canvas element is a rectangular area where graphics can be drawn using JavaScript. It allows developers to create dynamic, interactive, and graphical content on the web.

What are some common uses of the HTML5 Canvas element?

+

The HTML5 Canvas element can be used to create a wide range of applications, including simple drawings, animations, image manipulation, interactive graphics, and games.

How do I get started with using the HTML5 Canvas element?

+

To get started with using the HTML5 Canvas element, you will need to create a canvas element in your HTML file and get a reference to the 2D drawing context using JavaScript. You can then use the various methods and properties of the canvas context to draw graphics and manipulate images.