The HTML <canvas> element is used to draw graphics on a web page. Graphics are created using JavaScript.
HTML Canvas allows you to draw:
<canvas id="myCanvas" width="200" height="100"> </canvas>
A canvas is a rectangular drawing area.
<canvas id="canvas1" width="300" height="150" style="border:1px solid black;"> </canvas>
Always specify:
JavaScript accesses the drawing area using getContext().
var c=
document.getElementById(
"myCanvas"
);
var ctx=
c.getContext("2d");
The 2D context is used for drawing.
<canvas id="myCanvas" width="400" height="300" style="border:1px solid black;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Draw a rectangle
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 150, 100);
// Write text
ctx.font = "20px Arial";
ctx.fillStyle = "white";
ctx.fillText("Hello", 90, 110);
</script>
======================================== ctx.fillRect() – Draw a filled rectangle. ctx.strokeRect() – Draw a rectangle outline. ctx.beginPath() – Start a new path. ctx.arc() – Draw a circle. ctx.fillText() – Write text.
<canvas id="myCanvas" width="300" height="200" style="border:1px solid black;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(
95, // x-coordinate of the center
50, // y-coordinate of the center
40, // radius
0, // starting angle (0 radians)
2 * Math.PI // ending angle (360°)
);
ctx.stroke(); // Draw the outline border on circle
</script>
The arc() method creates circles and arcs.
The fillRect() method draws a filled rectangle.
<canvas id="myCanvas" width="300" height="200" style="border:1px solid black;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillRect(20, 20, 150, 100);
</script>
Parameters:
Canvas can display text.
<canvas id="myCanvas" width="300" height="150" style="border:1px solid black;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Set the font
ctx.font = "30px Arial";
// Draw the text
ctx.fillText("Hello", 20, 50);
</script>
fillText() draws filled text.
Images can be displayed inside a canvas.
<canvas id="myCanvas" width="400" height="300" style="border:1px solid #000;">
</canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.onload = function () {
ctx.drawImage(img, 70, 50, 250, 200);
};
img.src = "a.png";
</script>
drawImage() places the image on the canvas.
| Feature | Purpose |
|---|---|
| Line | Draw lines |
| Rectangle | Draw boxes |
| Circle | Draw circles |
| Text | Display text |
| Image | Display images |
| Fill | Fill color |
| Stroke | Draw outlines |
| Animation | Create motion |
Which method is used to get the 2D drawing context?