Once a
canvas is created, JavaScript is used to draw shapes on it.
1 - Drawing a Line
Copy and paste the code below in Notepad++ (or any other HTML5 editor) and run it.
<!DOCTYPE html>
<html>
<body>
<canvas id="myFirstCanvas" width="300" height="300" style="border:4px solid #0000ff;">
This browser does not support the HTML5 canvas tag. </canvas>
<script>
// create a context first
var canvas1 = document.getElementById("myFirstCanvas");
var context1 = canvas1.getContext("2d");
// then draw shapes
context1.strokeStyle = "red";
context1.lineWidth = 1;
context1.moveTo(0,0);
context1.lineTo(200,100);
context1.stroke();
</script>
</body>
</html>
Explanations
Note: a line starting with // is a comment. Comments are used to make the program easy to understand.
The statement
var canvas1 = document.getElementById("myFirstCanvas"); identifies the canvas to be used for drawing by its Id, in this case "myFirstCanvas".
The statement
var context1 = canvas1.getContext("2d"); creates an object called context1 that has the properties and methods for drawing, writing, ...
context1.strokeStyle = "red"; defines the color to be used for drawing.
context1.lineWidth = 1; defines the width of the drawing.
context1.moveTo(0,0); move the drawing to the point (0,0).
context1.lineTo(200,100); define what to draw, here it is a line.
context1.stroke(); does the actual drawing.
When the above program is run, the canvas with a red line as shown below will be displayed on the screen of your computer.
.
2 - Draw more than one Shape
More than one shape could be drawn in the same canvas.
Copy and paste the code below in Notepad++ (or any other HTML5 editor) and run it.
<!DOCTYPE html>
<html>
<body>
<canvas id="myFirstCanvas" width="300" height="300" style="border:4px solid #000000;">
This browser does not support the HTML5 canvas tag. </canvas>
<script>
var canvas1 = document.getElementById("myFirstCanvas");
var context1 = canvas1.getContext("2d");
// Draw the first shape
context1.beginPath();
context1.strokeStyle = "red";
context1.lineWidth = 1;
context1.moveTo(0,0);
context1.lineTo(200,100);
context1.stroke();
// Draw the second shape
context1.beginPath();
context1.strokeStyle = "blue";
context1.lineWidth = 3;
context1.moveTo(0,0);
context1.lineTo(200,200);
context1.stroke();
</script>
</body>
</html>
Explanations
The statement
context1.beginPath(); creates a path for each item to be drawn.
When the above program is run, the canvas with a red line and a blue line, as shown below, will be displayed on the screen of your computer.
.
More
Free HTML5 Canvas Tutorials