HTML canvas
Created By: chatGPT
HTML Canvas is an element that allows you to draw graphics and render visual images via scripting (usually JavaScript). You can create shapes, animations, and even complex graphics on the fly. The canvas element is simply a rectangular area on your HTML page where you can control the pixels directly.
<canvas id="myCanvas" width="500" height="300" style="border:1px solid #000000;"></canvas>
To start utilizing the canvas, you'll need to get a reference to it in your JavaScript code. You can achieve this using
getElementById()
and then accessing the getContext()
method to draw. The context will provide various methods for drawing shapes, text, images, and more.var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
Drawing shapes is straightforward. Here is how you can draw a rectangle and a circle on the canvas. The context's
fillRect()
method is used for rectangles, and arc()
is used for circles.// Draw a filled rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 150, 100);
// Draw a filled circle
ctx.beginPath();
ctx.arc(240, 50, 40, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
To add text, you can use the
fillText()
method that allows you to specify the font size, style, and color before drawing the string.ctx.font = '20px Arial';
ctx.fillStyle = 'green';
ctx.fillText('Hello Canvas!', 10, 50);
Animations can be implemented using the
requestAnimationFrame()
function which allows for smooth updates. You can clear the previous frame and redraw the updated graphics.function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Your drawing code here
requestAnimationFrame(draw);
}
draw();
Using images in the canvas is also possible. You can load images using the
Image
object and then draw them using the drawImage()
method.var img = new Image();
img.src = 'path/to/image.jpg';
img.onload = function() {
ctx.drawImage(img, 10, 10);
};