JavaScript Lesson 31: Creating Graphics Part 1

<Previous Lesson> [Table of Contents] <Next Lesson>

We can use JavaScript to draw graphics on an HTML document. In this lesson, we shall learn how to draw straight lines, triangles, and rectangles with outlines only.

Before we can draw graphics on an HTML document, first we need to create a canvas using the <canvas> element. However, we cannot draw any graphics with the Canvas element alone. In order to draw on the canvas, we need to use JavaScript.

To create the canvas, use the following HTML statement

<canvas id=”myCanvas” width=”300″ height=”150″ style=”border:1px solid #d3d3d3; background-color:beige;”>

It creates a canvas with width=300 px and height=150 px. We specify the border style and color as well as background color using the style attribute.

31.1: Drawing a Straight Line

To draw a straight line, create the DrawLine function as follows:

function DrawLine()
{
var c = document.getElementById("myCanvas");
var cx = c.getContext("2d");
cx.beginPath();
cx.moveTo(80, 20);
cx.lineTo(120, 100);
cx.stroke();
}

The getElementById() method returns the canvas element that has the id attribute with the the name myCanvas .

The getContext() method returns an object that provides methods and properties for drawing on the canvas.

beginPath begin the drawing and MoveTo specify the starting point while lineTo specifies the ending point. The Stroke method actually draws the line on the canvas.

The full JavaScript code integrated with the HTML document is as follows:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3; background-color:beige;">
</canvas><br><br>
<input type="button" Value="Draw Line" Onclick="DrawLine()">

<script>
function DrawLine()
{
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(80, 20);
ctx.lineTo(120, 100);
ctx.stroke();
}

</script>

</body>

</html>

The Output


You can also specify the width of the line using the lineWidth attribute, as follows:

ctx.lineWidth = 4;

Now add this line to the previous JavaScript function.
The Output



Drawing a Triangle

Based on the same principle, we can draw a triangle by joining three straight lines. The JavaScript is as follows:

<canvas id="myCanvas2" style="border: 1px solid #d3d3d3; background-color: beige;" width="300" height="150">
</canvas>
<input type="button" value="Draw Line" onclick="DrawTri()"/>
<script>

function DrawTri()
{
var c = document.getElementById("myCanvas2");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(80, 20);
ctx.lineTo(80, 100);
ctx.lineTo(130, 100);
ctx.lineTo(80, 20);
ctx.stroke();
}
</script>








<Previous Lesson> [Table of Contents] <Next Lesson>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on Reddit