Canvas is a html5 API which deals with drawing graphics with javascript. We can use this API to draw graphs, photo editing and animation. So in this tutorial, we will cover how to deal with 2D graphics.
Prerequisite
- Text editor
- Browser (Chrome)
Get Started
<!DOCTYPE html>
<html lang="en">
<head>
<style>
canvas { border: 1px solid black;}
</style>
</head>
<body>
<canvas id="page"></canvas>
<script>
(function () {
var canvas, ctx;
function Main() {
canvas = document.getElementById('page');
ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(300, 0, 0)';
ctx.fillRect(20, 20, 40, 40);
ctx.fillStyle = 'rgba(0, 0, 300, 0.5)';
ctx.fillRect(30, 30, 40, 40);
}
window.addEventListener("load", Main, false);
}());
</script>
</body>
</html>
In the above code, you can see the canvas tag with the id attribute but we should keep in mind the default height and width are 300px × 150px (width × height). We can change using height and width attributes.
Shapes
Using canvas API we can use a lot of shapes like rectangles, triangles, lines, arcs and curves But one thing that should keep in mind the coordinate system of canvas start from the top left corner and the left to right is x coordinate and top to bottom is y coordinate.
Rectangles
To create rectangles we can use –
- fillRect(x, y, width, height) – Draws a filled rectangle.
- strokeRect(x, y, width, height) – Draws a rectangular outline.
- clearRect(x, y, width, height) – Clears the rectangular area
ctx.fillRect(20, 20, 100, 100);
ctx.clearRect(30, 30, 60, 60);
ctx.strokeRect(40, 40, 40, 40);
Paths
A path is a list of points by which we can create different kinds of shapes so for that we can use –
- beginPath() – Creates a new path
- closePath() – Close the path and create new sub path
- stroke() – Draw shape using stroke
- fill() – Draw solid shape
ctx.fillStyle = 'rgb(100, 50, 50)';
ctx.moveTo(75, 50);
ctx.lineTo(100, 75);
ctx.lineTo(100, 25);
ctx.fill();
Lines
For line we can use
- lineTo(x, y) – drawa a line
// Triangle
ctx.fillStyle = 'rgb(100, 50, 50)';
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(100, 25);
ctx.lineTo(20, 100);
ctx.fill();
Drawing text
We have –
- fillText(text, x, y [, maxWidth]) – text filled using current fillstytle
- strokeText(text, x, y [, maxWidth]) – text filled using strokes
// without stroke
ctx.font = '48px serif';
ctx.fillText('Hello world', 10, 50);
// with stroke
ctx.font = '48px serif';
ctx.strokeText('Hello world', 10, 50);