HTML Canvas Tutorial
HTML Canvas Tutorial
The HTML Canvas is a powerful tool for creating dynamic and interactive graphics. Let's explore it step by step:
Drawing on the Canvas
Rectangles
You can draw rectangles like this:
ctx.fillRect(20, 20, 150, 100);
Lines
You can draw lines like this:
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(200, 50);
ctx.stroke();
Arcs / Circles
You can draw circles like this:
ctx.beginPath();
ctx.arc(100, 50, 50, 0, 2 * Math.PI);
ctx.stroke();
Changing Colors
You can change the fill color like this:
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 150, 100);
Drawing Images
You can draw images onto the canvas like this (replace the image source with your actual image path):
let img = new Image();
img.src = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2DEeFKNOoVcIrAmoUxAvjIjRjxW82SiZ08JYsjx2cvAhZ7Ul60eV_G02IjjlLQ4NU-fp2ASSlEEdTaNCUBaYd1-QwP9x1DZDV_H4dg8seFVObVE4xPumMFanTC2RwUw1J7VMT4s0yjYxDFTvoi5FWdyheCbISOJ9ZEaNXPb_-6YbxyaHqC8Vhi41_HZ4a/s1600/rabbit1.png';
img.onload = function() {
ctx.drawImage(img, 20, 20);
}
Creating Animations
You can create animations by continuously clearing and redrawing the canvas. Here's a simple animation:
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 1;
requestAnimationFrame(animate);
}