Science Knowings: HTML Course For Social Media

HTML Canvas

Goodbye HTML Audio and Video, Hello HTML Canvas!

<canvas id="myCanvas" width="500" height="500"></canvas>

With this code snippet, we're now ready to explore the world of graphics and interactivity with HTML Canvas!

What is HTML Canvas?

The HTML Canvas element is a rectangular area on a webpage where you can draw graphics using JavaScript. It provides a powerful API for creating dynamic and interactive visual content.

Creating a Canvas Element

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

This code grabs the reference to our canvas element from the HTML document and sets up a drawing context to start drawing.

Drawing Shapes Using Canvas

ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, false);
ctx.fillStyle = "red"; ctx.fill();

With this code, we've drawn a red circle on the canvas using the arc() method.

Filling and Stroking

ctx.beginPath();
ctx.rect(100, 100, 100, 100);
ctx.fillStyle = "blue"; ctx.fill();
ctx.strokeStyle = "green"; ctx.stroke();

Here, we've created a blue rectangle and added a green border using fill() and stroke().

Transformations in Canvas

Canvas allows you to rotate, translate, and scale your drawings using methods like translate(), rotate(), and scale().

ctx.translate(50, 50); // Moves the drawing 50px to the right and down

Animation with Canvas

function animate() {
  ... // Animation code
  requestAnimationFrame(animate);
}

To create animations, use requestAnimationFrame() to continuously update and draw on the canvas.

Canvas Event Handling

canvas.addEventListener('click', function(e) { ... });

Canvas supports event listeners, allowing you to respond to user interactions like clicks, mouse movements, and touch events.

Responsive Canvas

You can make your canvas responsive by setting its width and height to '100%'. The canvas will automatically resize to fit its container.

<canvas id="myCanvas" width="100%" height="100%"></canvas>

Next Up: HTML Drag and Drop

In the next session, we'll dive into HTML Drag and Drop. Learn how to make your web pages interactive by allowing users to drag and drop elements for exciting new possibilities!

Follow us to stay updated!