Draw a rectangle on the HTML5 canvas

Fetches the canvas element. Creates a 2D context. Clears the canvas, then sets the fill style to red and then fills the rectangle with the selected color.
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="300"></canvas>
    <script>

    var canvas = document.getElementById('myCanvas'); 
    var ctx = canvas.getContext('2d'); 

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'red';
    ctx.fillRect(25, 25, 100, 100); 

   </script>
  </body>
</html>     

Responses

0 Replies