Styling Shapes: Colors, Gradients, and Patterns
Explore different ways to style your shapes with colors, gradients (linear and radial), and repeating patterns to enhance visual appeal.
Styling Shapes: Colors in Canvas
This section will explore how to apply solid colors to fill and stroke shapes on the HTML5 Canvas. We'll cover different ways to specify colors, including hexadecimal, RGB, and named color values.
Understanding Color Values
The Canvas API provides properties like fillStyle
and strokeStyle
to define the colors used for filling and stroking shapes, respectively. These properties accept different color value formats:
- Hexadecimal Colors: Represented using a '#' followed by six hexadecimal digits (0-9 and A-F). The first two digits represent red, the next two green, and the last two blue. For example,
#FF0000
is red,#00FF00
is green, and#0000FF
is blue. - RGB Colors: Represented using the
rgb()
function, taking three arguments: red, green, and blue. Each value ranges from 0 to 255. For example,rgb(255, 0, 0)
is red,rgb(0, 255, 0)
is green, andrgb(0, 0, 255)
is blue. - Named Colors: Predefined color names, such as
"red"
,"green"
,"blue"
,"orange"
, etc. A list of valid named colors can be found online (e.g., on the MDN Web Docs).
Applying Colors to Shapes
Here's how to use these color values with fillStyle
and strokeStyle
:
Example: Drawing Colored Rectangles
This example will draw three rectangles with different fill colors.
JavaScript Code Example
The following JavaScript code demonstrates how to draw colored rectangles on the canvas:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Rectangle with hexadecimal fill color
ctx.fillStyle = '#FF0000'; // Red
ctx.fillRect(10, 10, 80, 80);
// Rectangle with RGB fill color
ctx.fillStyle = 'rgb(0, 255, 0)'; // Green
ctx.fillRect(110, 10, 80, 80);
// Rectangle with named color fill
ctx.fillStyle = 'blue';
ctx.fillRect(210, 10, 80, 80);
// Rectangle with a stroke color
ctx.strokeStyle = 'purple';
ctx.lineWidth = 5; // set line width for stroking
ctx.strokeRect(10, 110, 80, 80);
// Rectangle with both fill and stroke
ctx.fillStyle = 'orange';
ctx.fillRect(110, 110, 80, 80);
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.strokeRect(110, 110, 80, 80);
Explanation:
- We first get a reference to the canvas element and its 2D rendering context.
- We then set the
fillStyle
property to different color values (hexadecimal, RGB, and named). - The
fillRect()
method draws a filled rectangle at the specified coordinates and dimensions. - The
strokeStyle
property defines the color used for the stroke. - The
lineWidth
property sets the width of the stroke. - The
strokeRect()
method draws the outline of a rectangle.