The difference between the canvas fillRect(), strokeRect() and rect() functions

Written by Richard Heyes, on 28th January 2013

This page explains the difference between the fillRect(), strokeRect() and rect() functions.

These functions may generate confusion at first but the difference between them isn't hard to understand. The strokeRect() and fillRect() functions draw a rectangle on to the canvas immediately at the point in time that you call them. Like this:

    // First rectangle
    context.strokeStyle = 'red';
    // Second rectangle
    context.fillStyle = 'red';
[No canvas support]
[No canvas support]

The rect() function on the other hand is a "path" function - ie you use it when building paths. It doesn't draw anything to the canvas until you call the stroke() or fill() functions.

    co = document.getElementById("cvs3").getContext('2d');
    co.strokeStyle = 'red';
    // The rectangle could be filled as well if required
[No canvas support]

Slightly more code - but you do get the ability to combine the rectangle with other shapes before drawing them on to the canvas.

Don't forget - the canvas anti-aliasing means that lines appear a little thicker than the requested lineWidth. You can get around this by translating by half a pixel before you draw anything and then ensuring your coordinates are always whole numbers (using Math.round() for example).

context.translate(0.5, 0.5);