Fill and stroke

By Martin McBride, 2017-04-09
Tags: html canvas
Categories: graphics html canvas

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

See also

Sign up to the Creative Coding Newletter

Join my newsletter to receive occasional emails when new content is added, using the form below:

Popular tags

555 timer abstract data type abstraction addition algorithm and gate array ascii ascii85 base32 base64 battery binary binary encoding binary search bit block cipher block padding byte canvas colour coming soon computer music condition cryptographic attacks cryptography decomposition decryption deduplication dictionary attack encryption file server flash memory hard drive hashing hexadecimal hmac html image insertion sort ip address key derivation lamp linear search list mac mac address mesh network message authentication code music nand gate network storage none nor gate not gate op-amp or gate pixel private key python quantisation queue raid ram relational operator resources rgb rom search sort sound synthesis ssd star network supercollider svg switch symmetric encryption truth table turtle graphics yenc