Tech and Media Labs
This site uses cookies to improve the user experience.

HTML5 Canvas: Stroke and Fill

Jakob Jenkov
Last update: 2014-06-15

Whenever drawing shapes on an HTML5 canvas, there are two properties you need to set:

  1. Stroke
  2. Fill

The stroke and fill determines how the shape is drawn. The stroke is the outline of a shape. The fill is the contents inside the shape.

Here is an example rectangle drawn with blue stroke, and green fill (actually it is two rectangles):

HTML5 Canvas not supported

Here is the code that drew these two boxes:

// 1. wait for the page to be fully loaded.
window.onload = function() {

function drawExamples(){

    // 2. Obtain a reference to the canvas element.
    var canvas  = document.getElementById("ex1");

    // 3. Obtain a 2D context from the canvas element.
    var context = canvas.getContext("2d");

    // 4. Draw grahpics.
    context.fillStyle = "#009900";
    context.fillRect(10,10, 100,100);

    context.strokeStyle = "#0000ff";
    context.lineWidth   = 5;
    context.strokeRect(10,10, 100,100);

Notice how the stroke style and fill style are set separately, using the strokeStyle and fillStyle properties of the 2D context.

Also notice how the width of the stroke (the outline) of the blue rectangle is set using the lineWidth property. The lineWidth is set to 5, which means that the line width of the outlined rectangle will be 5.

Finally, notice how the 2D context is instructed to either draw a filled rect or a stroked rect.

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC