Create HTML 5 Canvas

SEARCH THIS SITE

Custom Search

We create our canvas using the HTML 5 element <canvas>.

1 - Creating one Canvas


You first need to know how to use the HTML editor Notepad++, or any other editor, in order to run HTML files including JavaScript programs (Getting Started with JavaScript).


Copy and paste the code below, paste in Notepad++ (or any other HTML5 editor) and run it.
<!DOCTYPE html>
<html>
<body>
<canvas id="myFirstCanvas" width="500" height="300" style="border:4px solid #000000;">
This browser does not support the HTML 5 canvas tag.
</canvas>
</body>
</html>

The element <canvas id="myFirstCanvas" width="500" height="300" style="border:4px solid #000000;"> in the above program is the one that creates the canvas having an ID "myFirstCanvas", a width of 500 pixels and a height of 300 pixels, a border of width 4 pixels and black color whose code is "#000000;". When run, the above code shows a 500 by 300 pixels rectangle with black border of width 4 pixels as shown below.

one canvas.

2 - Creating more than one Canvas


We can use table or div elements in html to create and position several canvases. An example is shown below with two canvases side by side. Copy the code below and paste in Notepad++ and run.


<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<td>
<canvas id="myFirstCanvas" width="300" height="300" style="border:4px solid #0000ff;">
This browser does not support the HTML5 canvas tag. </canvas>
</td>
<td width="300" align="top">
<canvas id="mySecondCanvas" width="400" height="300" style="border:4px solid #ff0000;">
This browser does not support the HTML5 canvas tag. </canvas>
</td>
</tr>
</table>
</body>
</html>

When run, the above code shows a 300 by 300 pixels rectangle with blue border of width 4 pixels on the left and second 400 by 300 pixels rectangle with red border.

two canvases.

Now that you know how to create a canvas, let next see what can be included in a canvas.

More Free HTML5 Canvas Tutorials