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 to create a basic canvas and draw circles.
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. 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.
Next part of this will be in a video on my YouTube channel. Stay tuned.
In other news
Recently, I have been feeling burnt out. As part of sustainably managing everything that is going in my life, I wanted to share with my community that I will be publishing this newsletter once a month going forward. Staring next month, you will also notice a different format that I think would make the most of your time. The format will be -
A short bite sized Front End Development post.
A list of 3 noteworthy Front End blog posts / youtube videos / news from the community in the last 30 days.
A photo from my life, to show you the person behind this newsletter. ❤️
Thank you for being part of my community.
Let's be kind to each other. We are all doing our best.