WikiGalaxy

Personalize
HTML Canvas

HTML Canvas

Introduction:

The <canvas> element is used to draw graphics on a web page via scripting. It allows for rendering shapes, images, text, and animations with JavaScript.

Creating a Simple Canvas:

1. Basic Canvas Setup

To start using a canvas, add the <canvas> element to your HTML with a specified width and height.


<canvas id="myCanvas" width="200" height="100">Your browser does not support HTML5 canvas.</canvas>

2. Drawing a Rectangle

Using JavaScript, you can draw shapes like rectangles on the canvas. Access the 2D drawing context with getContext('2d').


var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#FF0000';
ctx.fillRect(20, 20, 150, 75);

3. Drawing a Line

You can draw lines by using the beginPath() and lineTo() methods.


ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

4. Drawing a Circle

Circles can be drawn using the arc() method, specifying the center coordinates, radius, and starting and ending angles.


ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

5. Adding Text

Use the fillText() method to add text. Customize with font properties and colors.


ctx.font = '30px Arial';
ctx.fillText('Hello Canvas', 10, 50);

Conclusion:

The canvas element is versatile and allows for dynamic, scriptable rendering of 2D shapes and images on a web page, providing a foundation for interactive graphics.


// JavaScript code to execute the drawing functions
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Draw a red rectangle
ctx.fillStyle = '#FF0000';
ctx.fillRect(20, 20, 150, 75);
// Draw a line
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
// Draw a circle
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
// Add text
ctx.font = '30px Arial';
ctx.fillText('Hello Canvas', 10, 50);
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025