3 years ago
Shahzad Gujjar
2,864 Views
6
In this tutorial, you’ll learn how to use the HTML5 canvas element to draw graphics on a web page.
What is Canvas?
JavaScript can be used to draw graphics on the webpage using the HTML5 canvas element. Apple first introduced the canvas in Mac OS for dashboard widgets and to power graphics in the Safari web browser. Firefox, Google Chrome, and Opera all adopted it later. The canvas is now used in HTML5, the latest specification for next-generation web technologies.
The canvas> element has a width of 300px and a height of 150px by default, with no border or content. The CSS height and width property, on the other hand, can be used to define custom width and height, while the CSS border property can be used to apply a border.
Understanding Canvas Coordinates
The canvas is a rectangular two-dimensional area. The origin coordinates for the top-left corner of the canvas are (0, 0), and the coordinates for the bottom-right corner are (0, 0). (canvas width, canvas height). Here’s a quick example of the canvas default coordinate system.
CANVAS
Place your mouse pointer inside the canvas area shown above, and you’ll see the current coordinates of the canvas. All major web browsers, including Chrome, Firefox, Safari, Opera, and Internet Explorer 9 and above, support the <canvas> element.
Drawing Path and Shapes on Canvas
In this section, we’ll look at how to use the newly introduced HTML5 canvas element and JavaScript to draw basic paths and shapes.
The base template for drawing paths and shapes on the 2D HTML5 canvas is available here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Drawing on Canvas - Learn Code Web</title>
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// draw stuff here
};
</script>
</head>
<body>
<canvas id="myCanvas" width="300" height="200"></canvas>
</body>
</html>
Except for lines 7 to 11, the rest of the lines are fairly straightforward. When the page loads, the anonymous function is attached to the window.onload event will execute. We can use the document.getElementById() method to get to the canvas element once the page has loaded. Bypassing 2d to the canvas object’s getContext() method, we later defined a 2D canvas context.
Drawing a Line
A straight line is the most basic path you can draw on the canvas. The most important methods for this are moveTo(), lineTo(), and the stroke ().
The moveTo() method establishes the position of the drawing cursor on the canvas, while the lineTo() method establishes the coordinates of the line’s endpoint, and the stroke() method establishes the line’s visibility. Let’s take a look at an example:
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.moveTo(50, 150);
context.lineTo(250, 50);
context.stroke();
};
</script>
Drawing a Arc
The arc() method can be used to construct arcs. This method’s syntax is as follows:
context.arc(centerX, centerY, radius, startingAngle, endingAngle, counterclockwise);
In the example below, the JavaScript code will draw an arc on the canvas.
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.arc(150, 150, 80, 1.2 * Math.PI, 1.8 * Math.PI, false);
context.stroke();
};
</script>
Drawing a Rectangle
The rect() method can be used to make a rectangle and square shapes. The rectangle’s x, y, width, and height are the four parameters required by this method.
The following is the basic syntax for the rect() method:
context.rect(x, y, width, height);
The JavaScript code below will draw a rectangle shape in the middle of the canvas.
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.rect(50, 50, 200, 100);
context.stroke();
};
</script>
Drawing a Circle
There is no equivalent to the rectangle’s rect() method for creating circles. The arc() method, on the other hand, can be used to create a fully enclosed arc, such as a circle.
The following is the syntax for drawing a full circle with the arc() method:
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
The illustration below will draw a full circle in the centre of the canvas.
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.arc(150, 100, 70, 0, 2 * Math.PI, false);
context.stroke();
};
</script>
Applying Styles and Colors on Stroke
The stroke’s default color is black, and its thickness is one pixel. However, the strokeStyle and lineWidth properties can be used to adjust the color and width of the stroke, respectively.
An orange line with 5 pixels of width will be drawn in the following example.
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.lineWidth = 5;
context.strokeStyle = "orange";
context.moveTo(50, 150);
context.lineTo(250, 50);
context.stroke();
};
</script>
The lineCap property may also be used to set the cap style of the lines. The line caps come in three different styles: butt, round, and square. Here’s an illustration:
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.lineWidth = 10;
context.strokeStyle = "orange";
context.lineCap = "round";
context.arc(150, 150, 80, 1.2 * Math.PI, 1.8 * Math.PI, false);
context.stroke();
};
</script>
Filling Colors inside Canvas Shapes
The fillStyle() method can also be used to fill color within canvas shapes.
The following example shows how to fill a rectangle shape with a solid color.
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.rect(50, 50, 200, 100);
context.fillStyle = "#FB8B89";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
};
</script>
NOTE: It is recommended to use the fill() method before the stroke() method while styling shapes on canvas in order to render the stroke correctly.
You may also use the fillStyle() method to fill a circle with a solid color.
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.arc(150, 100, 70, 0, 2 * Math.PI, false);
context.fillStyle = "#FB8B89";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
};
</script>
Filling Gradient Colors inside Canvas Shapes
You may also use a gradient color to fill the shapes on the canvas. A gradient is like a smooth visual transition from one colour to the next. There are two different types of gradients: linear and radial.
The following is the basic syntax for creating a linear gradient:
var grd = context.createLinearGradient(startX, startY, endX, endY);
The createLinearGradient() method is used to fill a linear gradient color within a rectangle in the following example. Let’s take a look at how it works in practice:
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.rect(50, 50, 200, 100);
var grd = context.createLinearGradient(0, 0, canvas.width, canvas.height);
grd.addColorStop(0, '#8ED6FF');
grd.addColorStop(1, '#004CB3');
context.fillStyle = grd;
context.fill();
context.stroke();
};
</script>
Similarly, the createRadialGradient() method can be used to fill canvas shapes with a radial gradient. The following is the basic syntax for creating a radial gradient:
var grd = context.createRadialGradient(startX, startY, startRadius, endX, endY, endRadius);
The createRadialGradient() method is used to fill a radial gradient color within a circle in the following example. Let’s put it to the test to see how it really works:
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.arc(150, 100, 70, 0, 2 * Math.PI, false);
var grd = context.createRadialGradient(150, 100, 10, 160, 110, 100);
grd.addColorStop(0, '#8ED6FF');
grd.addColorStop(1, '#004CB3');
context.fillStyle = grd;
context.fill();
context.stroke();
};
</script>
Drawing Text on Canvas
Text can also be drawn on the canvas. Any Unicode characters can be used in these texts. On a canvas, the following example will draw a simple greeting message “Hello World!”
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.font = "bold 32px Arial";
context.fillText("Hello World!", 50, 100);
};
</script>
You may also change colors and alignment of the text on the canvas, as shown below:
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.font = "bold 32px Arial";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "orange";
context.fillText("Hello World!", 150, 100);
};
</script>
The strokeText() method can also be used to apply a stroke on text. Instead of filling the text, this method would colour the perimeter. However, you can use the fillText() and strokeText() methods together to set both the fill and stroke on canvas text.
<script>
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.font = "bold 32px Arial";
context.textAlign = "center";
context.textBaseline = "middle";
context.strokeStyle = "orange";
context.strokeText("Hello World!", 150, 100);
};
</script>
In order to render the stroke correctly when styling text on canvas, it is recommended to use the fillText() method before the strokeText() method.
3 years ago
Shahzad Gujjar
2,864 Views
6