The difference between the canvas fillRect, strokeRect and rect functions

  Read comments... Posted on 28th January 2013

Summary
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:

<script>
    // First rectangle
    context.strokeStyle = 'red';
    context.strokeRect(35,35,30,30);
    
    // Second rectangle
    context.fillStyle = 'red';
    context.fillRect(35,35,30,30);
</script>
[No canvas support]
context.strokeRect()
[No canvas support]
context.fillRect()

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.

<script>    
    co = document.getElementById("cvs3").getContext('2d');
    
    co.strokeStyle = 'red';
    
    co.beginPath();
        co.rect(35,35,30,30);
    co.stroke();
    
    // The rectangle could be filled as well if required
    //co.fill();
</script>
[No canvas support]
context.rect()

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);
Share RGraph
X

Comments