Introduction to HTML Canvas and Canvas APIs

HTML Canvas is a powerful tool for creating dynamic graphics and animations using JavaScript on web pages. It can be used to create data visualizations, augmented reality experiences, games, simulations, process images, manipulate videos on the fly and create digital art. The possibilities are endless! In this short post, we will look at how a basic HTML shape, and create an animating ball.

Basics of canvas

To get started with canvas, you'll need to create a canvas element

<canvas id="canvas"> </canvas>

and get access to the canvas's context in your HTML code. Context gives us access to APIs that render the graphics on the canvas.

const canvas = document.getElementById('canvas')
const context = canvas.getContext('2d')

Drawing shapes

Once we have access to context, we can begin drawing shapes. Let's draw a circle. We will be using the arc method on context. Let's create an circle with center at (0,0) and a radius of 20.

context.beginPath();
context.arc(0, 0, 20, 0, 2 * Math.PI, false);

Next, let's fill in the circle, and give it a stroke color.

context.fillStyle="red";
context.strokeStyle="red";

context.fill();
context.stroke();

We can move this to a click handler, so that whenever we click, we create a circle at our (x,y) coordinates.

const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const drawCircle = (event) => {
  const x = event.pageX;
  const y = event.pageY;
  const radius = 20;
  //arc
  context.beginPath();
  context.arc(x, y, radius, 0, 2 * Math.PI, false);

  context.fillStyle="red";
  context.fill();

  context.strokeStyle="red";
  context.stroke();


}

canvas.addEventListener('click', drawCircle);

And, that's all we need! Give it a go and see circles appearing on your canvas.

This is just the beginning though. Next time, we will use this to create animating balls on the screen.

Happy Learning!!!.