TenMinuteTutor

Coding, maths and art

Fill and stroke

Outlining a rectangle

In computer graphics, drawing a line around a shape is called stroking.

Here is the code to draw a line around a rectangle:

context.strokeStyle = 'deeppink';
context.lineWidth = 4;
context.strokeRect(50, 50, 75, 75);

We set the strokeStyle to the colour we want the line to be. Of course, just like fill, we can any of the ways to set the colour.

We also set the lineWidth of the stroke, in pixels.

Finally, we draw the line using strokeRect (rather than fillRect).

Filling a rectangle

We already know how to fill a rectangle:

context.fillStyle = 'cadetblue';
context.fillRect(150, 50, 75, 75);

Filling and stroking a rectangle

Here is how to fill and stroke a rectangle:

context.strokeStyle = 'black';
context.lineWidth = 2;
context.fillStyle = 'gold';
context.fillRect(250, 50, 75, 75);
context.strokeRect(250, 50, 75, 75);

We first set the required colours for fill and stroke, and the line width for the stroke.

Then we use fillRect to fill the shape, followed by strokeRect to draw the outline. These two calls use exactly the same parameters.

Code

Here is the complete code:

<!DOCTYPE HTML>
<html>
  <head>
  </head> 
  <body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        
        context.strokeStyle = 'deeppink';
        context.lineWidth = 4;
        context.strokeRect(50, 50, 75, 75);
        
        context.fillStyle = 'cadetblue';
        context.fillRect(150, 50, 75, 75);
        
        context.strokeStyle = 'black';
        context.lineWidth = 2;
        context.fillStyle = 'gold';
        context.fillRect(250, 50, 75, 75);
        context.strokeRect(250, 50, 75, 75);
        
    </script>
  </body>
</html>  

Here is the result:

image