HTML Canvas šŸŽÆ

beginner
17 min

HTML Canvas šŸŽÆ

Welcome to our deep dive into the fascinating world of HTML Canvas! This powerful tool allows you to create dynamic, interactive, and visually stunning graphics right in your web browser. Let's get started!

What is HTML Canvas? šŸ“

HTML Canvas is a web-based drawing tool, made possible by the HTML5 standard. It lets you create, modify, and animate graphics using JavaScript. With Canvas, you can:

  • Draw shapes (circles, rectangles, lines)
  • Create images and animations
  • Implement games and interactive web applications

Getting Started with HTML Canvas šŸ’”

Setting Up the Canvas

To use HTML Canvas, you'll first need to create an HTML file with a <canvas> element.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My First Canvas</title> </head> <body> <canvas id="myCanvas" width="500" height="500"></canvas> <script src="script.js"></script> </body> </html>

In this example, we've created an HTML document with a canvas element that has an ID of "myCanvas". We've also added a script tag for our JavaScript file, script.js.

Accessing the Canvas

To access the canvas in JavaScript, we use the document.getElementById() method:

javascript
const canvas = document.getElementById('myCanvas');

Drawing on the Canvas šŸŽØ

To draw on the canvas, we use the getContext() method to get a 2D drawing context. Once we have the context, we can use various methods to draw shapes, images, and more.

javascript
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d');

Drawing Basic Shapes šŸ’”

Now that we have our canvas and drawing context, let's create some simple shapes!

Lines šŸ”¢

Drawing a line is as easy as specifying the starting point and ending point of the line, along with a color.

javascript
ctx.beginPath(); ctx.moveTo(25, 25); ctx.lineTo(100, 100); ctx.strokeStyle = 'blue'; ctx.stroke();

Rectangles šŸ—ļø

Creating a rectangle involves defining its position, width, height, and color.

javascript
ctx.fillStyle = 'yellow'; ctx.fillRect(50, 50, 100, 100);

Circles 🌟

Drawing a circle requires defining its center, radius, and color. We can also use the arc() method to create the circle's outline.

javascript
ctx.beginPath(); ctx.arc(75, 75, 50, 0, Math.PI * 2); ctx.fillStyle = 'red'; ctx.fill(); ctx.stroke();

Quiz Time! šŸ“

Quick Quiz
Question 1 of 1

What method is used to create a line on the canvas?

Up Next: Manipulating Images and Animating šŸŽØšŸ•µļøā€ā™‚ļø

Stay tuned for our next lesson, where we'll dive deeper into working with images, animating graphics, and creating interactive web applications using HTML Canvas!

šŸŽ‰ Happy coding! šŸŽ‰