HTML5 Canvas Tutorial - HTML5 Canvas Rectangle








To create a rectangle using HTML5 Canvas, we can use the rect() method.

An HTML5 Canvas rectangle needs four parameters: x and y about its top left corner, and sized with width and height parameters.

Example


<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="500" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
<!-- w w  w .  j a  va 2s.  c  o m-->
      context.beginPath();
      context.rect(190, 50, 200, 100);
      context.fillStyle = 'red';
      context.fill();
      context.lineWidth = 7;
      context.strokeStyle = 'black';
      context.stroke();
    </script>
  </body>
</html>      

The code above is rendered as follows:





Example 2

The following code shows how to create shape structure.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500px' height='200px'/>
<script type='text/javascript'>
    function Shape(a,b,w,h,fill){<!-- ww  w  . ja v a  2s .  c  o m-->
      this.x = a; // change to this.x
      this.y = b; // change to this.y
      this.w = w;
      this.h = h;
      this.fill = fill;
    }
    canvas = document.getElementById("canvas");
    if (canvas.getContext){
        var myRect = [];
            myRect.push(new Shape(100, 0, 25, 25, "#333"));
            myRect.push(new Shape(0, 40, 39, 25, "#333"));
            myRect.push(new Shape(0, 80, 100, 25, "#333"));
        ctx = canvas.getContext("2d");
        for (i in myRect) {
          oblock = myRect[i];
          ctx.fillStyle = oblock.fill;
          ctx.fillRect(oblock.x,oblock.y,oblock.w,oblock.h);
          ctx.fillStyle="#CC00FF"; 
            ctx.fillRect(100,100,20,20); 
        }
    }
</script>
</body>
</html>

The code above is rendered as follows: