How to draw Rectangle?

Before dreaming about creating an interactive HTML5 games, let's start with the basic.

First, click the "Red Square" button, if you don't see a red square in the canvas, you problably want to get the right web browser to continue.

To draw anything in canvas, you do not put anything between the opening tag and closing tag of <canvas>, browsers that supports Canvas will just ignore it. You can only use Javascript to do your drawing.

Rule number one, your canvas element has got to have an ID, so we can use Javascript to locate it. Secondly, every canvas has what we call "Context". In fact, context of canvas is what we are going to paint on, not canvas itself.

var c1 = document.getElementById("c1");

var c1_context = c1.getContext("2d");

Let's choose use the red paint (fillStyle="#f00";) and paint a red square with 100px width and height. (fillRect(50, 50, 100, 100)).

c1_context.fillStyle = "#f00";

c1_context.fillRect(50, 50, 100, 100);

The table below shows the methods of drawing rectangle.

Methods of "Context"Descriptions
fillStyle CSS Color, pattern or gradient within the shape. Default fillStyle is solid black color.
strokeStyle Color or CSS style of the lines of the shape
fillRect(x, y, width, height) Draw a rectangle start from coordinate x and y and size of width x height.
strokeRect(x, y, width, height) Draw a rectangle with just its edges.
clearRect(x, y, width, height) Clear the area specified in x, y coordinate and area of width x height