English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML5 Canvas Stroke and Fill

Every time in HTML5When drawing shapes on the canvas, you need to set two properties: Stroke (outline) and Fill (fill)

Stroke and Fill properties

Every time in HTML5When drawing shapes on the canvas, you need to set two properties:

  1. Stroke

  2. Fill

Stroke (outline) and Fill (fill) determine how shapes are drawn. Stroke is the outline of the shape. Fill is the content inside the shape.

Online example

This is an example of a rectangle drawn with a blue outline and green fill (which are actually two rectangles):

This is the code to draw these two boxes:

<canvas id="ex1" width="500" height="150" style="border: 1px solid #cccccc;">
    HTML5 Canvas not supported
</canvas>
<script>
// 1.Wait for the page to fully load.
window.onload = function() {
    drawExamples();
}
function drawExamples(){
    // 2.Get a reference to the canvas element.
    var canvas = document.getElementById("ex1");
   // 3.Get the canvas element2D context.
    var context = canvas.getContext("2d");
    // 4.Draw graphics.
    context.fillStyle = "#00"9900";
    context.fillRect(10,10, 100,100);
    context.strokeStyle = "#0000ff";
    context.lineWidth = 5;
    context.strokeRect(10,10, 100,100);
}
</script>
Test and see ‹/›

The running results of the above example:

HTML5 Canvas not supported

Note how to use2The strokeStyle and fillStyle properties of the D context are used to set the stroke style and fill style, respectively.

Also note how to use the lineWidth property to set the stroke width (outline) of the blue rectangle. The lineWidth is set to5, which means the line width of the described rectangle is5.

.2The last thing to note is how to specify