HTML5 Game - Methods to draw Rectangles

Introduction

Rectangles are one of the most common and easiest to draw Canvas objects.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML> <html> 
<head>
<script>
window.onload = function()//from   ww  w .j a v  a2s . c  o  m
{ 
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

   //LAYOUT of first rectangle.
   let xPos  = 20;     
   let yPos   = 20;
   let width = 100;    
   let height = 50;

   //DISPLAY rectangles.
   context.fillStyle = "hotpink";
   context.fillRect(xPos,     yPos,    width,    height); 
   context.lineWidth= 4;
   context.strokeStyle = "royalblue";
   context.strokeRect(xPos+130, yPos,    width,    height);
   context.fillStyle= "darkorange";
   context.fillRect(xPos+260, yPos,    width,    height);
   context.clearRect(xPos+285, yPos+10, width-50, height-20);               
}
</script>
</head>
<body> 
<div style = "width:400px;  height:90px;  margin:0 auto;  padding:5px;">
<canvas id = "canvasArea" width  = "400"  height = "90"  style = "border:2px solid black">
Your browser doesn't currently support HTML5 Canvas.
</canvas>
</div> 
</body>
</html>

Note

Create your rectangles using the function for the type of rectangle desired:

Method
Usage
fillRect()

A rectangle that's filled as specified in attributes such as fillStyle.
context.fillRect(xPos, yPos, width, height);
strokeRect()

A rectangle that's outlined as specified in attributes such as strokeStyle and lineWidth.
context.strokeRect(xPos+130, yPos, width, height);
clearRect()

A rectangle that creates a cleared space.
context.clearRect(xPos+285, yPos+10, width-50, height-20);

Related Topic