HTML5 Tutorial - Canvas : Rectangle

Canvas : Rectangle

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.

<canvas id="c1" width="200" height="200" style="border:solid 1px #000000;"></canvas>
<button onclick="draw_square();return true;">Red Square</button> <script>
function draw_square() {
   var c1 = document.getElementById("c1");
   var c1_context = c1.getContext("2d");
   c1_context.fillStyle = "#f00";
   c1_context.fillRect(50, 50, 100, 100);
}
</script>

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
<div ><canvas id="Canvas2" width="200" height = "200" style="border:solid 1px #000000;"></canvas>
   <div>
     <button onclick="blue_square_2();return true;">Blue Square</button>
     <button onclick="red_stroke_2();return true;">Red Square</button>
     <button onclick="clear_rect_2();return true;">Erase Everything</button>
   </div>
</div>
<script>
   var c2 = document.getElementById("c2");
   var c2_context = c2.getContext("2d");
   function blue_square_2() { //Blue color square
     c2_context.fillStyle = "#00f";
     c2_context.fillRect(50, 50, 100, 100);
   }
   function red_stroke_2() { //Red color edges
     c2_context.strokeStyle = "#f00";
     c2_context.strokeRect(45, 45, 110, 110);
   }
   function clear_rect_2() { //Clear all
     c2_context.clearRect(40, 40, 120, 120);
   }
</script>