HTML5 Canvas: Drawing and styling a rectangle or square in a canvas

This entry is part 4 of 17 in the series HTML5 Canvas

Using fillRect(pos-x, pos-y, width, height), we can draw a rectangle or square.

This next example will create a 100 pixel by 100 pixel square and place it in the top-left corner
(0,0) of the canvas

<!DOCTYPE html>
<html lang='en'>
    <meta charset='utf-8'>
    <title> Canvas rectangle</title>
        canvas {
            border: 1px solid #000;
<canvas id='myCanvas' width='640' height='480'></canvas>
    var canvas = document.getElementById('myCanvas').getContext('2d');
    canvas.fillRect(0, 0, 100, 100);

The canvas.fillStyle=’red’ will fill the square red.

Series Navigation<< HTML5 Canvas: Canvas tools
HTML5 Canvas: Line tool and coordinates >>

Leave a comment

Leave a Reply