Colors on Canvas
6 of 10 lessons in Chapter 7: Drawing with JavaScript - Intro to Canvas
Learning Objectives
TrashyMcTweak
Alright people, our canvas is BORING! It's like watching paint dry, except the paint is invisible and NOTHING IS DRYING!
We need to add some COLOR to this digital wasteland! Let's make this canvas BLEED RAINBOWS!
CodyMcTweak
Um, I tried using color but all my rectangles are still black. I set fillStyle = "blue" but nothing changed...
const ctx = canvas.getContext('2d'); ctx.fillRect(10, 10, 100, 50); ctx.fillStyle = "blue"; ctx.fillRect(130, 10, 100, 50);
AllyMcTweak
That's because you're setting the fillStyle AFTER drawing your first rectangle. The order matters here!
You need to set the color first, then draw the shape that uses that color.
const ctx = canvas.getContext('2d'); // First rectangle (black by default) ctx.fillRect(10, 10, 100, 50); // Set color BEFORE drawing the second rectangle ctx.fillStyle = "blue"; ctx.fillRect(130, 10, 100, 50);
FattyMcTweak
Oh please, "blue"? That's amateur hour. If you want PREMIUM results, you need to use hex codes, RGB values, or better yet - gradients! Nobody pays top dollar for a color you can spell.
// Professional color options: ctx.fillStyle = "#4B0082"; // Indigo hex code ctx.fillStyle = "rgb(75, 0, 130)"; // RGB ctx.fillStyle = "rgba(75, 0, 130, 0.5)"; // RGBA with opacity
GrumpyMcTweak
Do you have ANY IDEA how VULNERABLE your color choices are?! What if someone injected MALICIOUS COLOR VALUES?!
At MINIMUM you should be validating all your hex codes! And don't even get me STARTED on gradient security!
AshleyMcTweak
Actually, according to the HTML Canvas API Specification section 4.8.11, the fillStyle and strokeStyle properties can accept any CSS color value, including named colors, hex, RGB, RGBA, HSL, and HSLA.
There's no specific security vulnerability related to color values in this context.
GarbageMcTweak
All this complication for something so simple... Look, there are only two properties you need to know: fillStyle and strokeStyle. One colors the inside of your shapes, the other colors the outlines.
Set them before you draw. That's it. Now can we move on to something actually challenging?
TrashyMcTweak
I'm going to create a MASTERPIECE with EVERY COLOR IN THE SPECTRUM! My canvas will be so vibrant it'll require a seizure warning!
RAINBOW EVERYTHING!!! 🌈
Canvas Color Basics
Before we create rainbow masterpieces, let's understand the two main properties for coloring in canvas:
fillStyle
Sets the color used to fill shapes
const ctx = canvas.getContext('2d'); ctx.fillStyle = "#4B0082"; // Indigo ctx.fillRect(50, 25, 200, 100);
strokeStyle
Sets the color used for shape outlines
const ctx = canvas.getContext('2d'); ctx.strokeStyle = "#FF4500"; // OrangeRed ctx.lineWidth = 5; ctx.strokeRect(50, 25, 200, 100);
Color Format Options
AllyMcTweak
There are several ways to specify colors in canvas. Let's look at the options:
Color Names & Hex Codes
// Named colors ctx.fillStyle = "red"; ctx.fillRect(25, 25, 100, 50); // Hex codes ctx.fillStyle = "#00BFFF"; // DeepSkyBlue ctx.fillRect(175, 25, 100, 50); // Short hex codes ctx.fillStyle = "#0F0"; // Green ctx.fillRect(25, 100, 100, 50); // Hex with alpha (transparency) ctx.fillStyle = "#8A2BE280"; // Semi-transparent blue ctx.fillRect(175, 100, 100, 50);
RGB, RGBA, HSL & HSLA
// RGB format ctx.fillStyle = "rgb(255, 165, 0)"; // Orange ctx.fillRect(25, 25, 100, 50); // RGBA format (with alpha/transparency) ctx.fillStyle = "rgba(128, 0, 128, 0.5)"; // Semi-transparent purple ctx.fillRect(175, 25, 100, 50); // HSL format (hue, saturation, lightness) ctx.fillStyle = "hsl(120, 100%, 50%)"; // Green ctx.fillRect(25, 100, 100, 50); // HSLA format (with alpha/transparency) ctx.fillStyle = "hsla(240, 100%, 50%, 0.5)"; // Semi-transparent blue ctx.fillRect(175, 100, 100, 50);
Canvas Gradients
FattyMcTweak
Solid colors are for amateurs! If you want TRULY premium visuals, you need to use gradients. It's like going from motel soap to a luxury spa experience.
TrashyMcTweak
FOR ONCE I AGREE! Gradients are where it's at! Let's make these canvas elements SHINE with color transitions that would make a unicorn jealous!
Linear Gradient
Transitions colors along a straight line
const ctx = canvas.getContext('2d'); // Create a linear gradient (x0, y0, x1, y1) const gradient = ctx.createLinearGradient(0, 0, 300, 0); // Add color stops gradient.addColorStop(0, "#FF8C00"); // DarkOrange gradient.addColorStop(1, "#8A2BE2"); // BlueViolet // Use gradient for fillStyle ctx.fillStyle = gradient; ctx.fillRect(0, 0, 300, 150);
Radial Gradient
Transitions colors from a center point outward
const ctx = canvas.getContext('2d'); // Create a radial gradient // (x0, y0, r0, x1, y1, r1) const gradient = ctx.createRadialGradient( 150, 75, 10, // Inner circle (x, y, radius) 150, 75, 150 // Outer circle (x, y, radius) ); // Add color stops gradient.addColorStop(0, "#FFFF00"); // Yellow gradient.addColorStop(1, "#FF1493"); // DeepPink // Use gradient for fillStyle ctx.fillStyle = gradient; ctx.fillRect(0, 0, 300, 150);
Multi-Stop Gradient Example
const ctx = canvas.getContext('2d'); // Create a horizontal rainbow gradient const rainbow = ctx.createLinearGradient(0, 0, 600, 0); rainbow.addColorStop(0, "#FF0000"); // Red rainbow.addColorStop(0.17, "#FF7F00"); // Orange rainbow.addColorStop(0.33, "#FFFF00"); // Yellow rainbow.addColorStop(0.5, "#00FF00"); // Green rainbow.addColorStop(0.67, "#0000FF"); // Blue rainbow.addColorStop(0.83, "#4B0082"); // Indigo rainbow.addColorStop(1, "#9400D3"); // Violet ctx.fillStyle = rainbow; ctx.fillRect(0, 0, 600, 150);
The Order Matters!
GarbageMcTweak
Let's address the elephant in the room - the mistake everyone makes with colors on canvas.
Order of Operations Demo
Watch what happens when you change the order of commands:
// Correct order: const ctx = canvas.getContext('2d'); // Set color FIRST ctx.fillStyle = "red"; // THEN draw the shape ctx.fillRect(50, 50, 150, 50); // Set a new color ctx.fillStyle = "blue"; // Draw another shape ctx.fillRect(250, 50, 150, 50); // Set stroke color and width ctx.strokeStyle = "green"; ctx.lineWidth = 5; // Draw the stroke ctx.strokeRect(450, 50, 100, 50);
Common Mistakes to Avoid:
- Setting the color after drawing the shape
- Forgetting to set colors for new shapes
- Confusing fillStyle (for fills) and strokeStyle (for outlines)
- Not setting lineWidth before using strokeStyle
Activity: Rainbow Color Picker
TrashyMcTweak
It's RAINBOW time, people! Let's build the most COLORFUL color picker the world has ever seen!
Build Your Own Rainbow Color Picker
1. Create Your Rainbow Palette
Use the sliders to build your perfect rainbow gradient:
2. Use Your Rainbow
Click anywhere on the canvas below to add colorful shapes:
3. Your Rainbow Code
Here's the code that creates your rainbow gradient:
const ctx = rainbowCanvas.getContext('2d'); // Create a horizontal rainbow gradient const rainbowGradient = ctx.createLinearGradient(0, 0, 400, 0); rainbowGradient.addColorStop(0, "#FF0000"); // Red rainbowGradient.addColorStop(0.2, "#FF7F00"); // Orange rainbowGradient.addColorStop(0.4, "#FFFF00"); // Yellow rainbowGradient.addColorStop(0.6, "#00FF00"); // Green rainbowGradient.addColorStop(0.8, "#0000FF"); // Blue rainbowGradient.addColorStop(1, "#8B00FF"); // Violet // Apply the gradient ctx.fillStyle = rainbowGradient; ctx.fillRect(0, 0, 400, 80);
CodyMcTweak
Wow, I think I finally get it! Set the color first, then draw the shape. And there are so many color formats to choose from!
AllyMcTweak
Exactly! And remember that fillStyle and strokeStyle can accept any CSS color value - named colors, hex codes, RGB values, or even gradients!
GrumpyMcTweak
At least SOME of you understand the IMPORTANCE of COLOR SECURITY! Always validate your hex codes and never trust user-supplied colors without proper sanitization!
FattyMcTweak
If you're not using gradients, are you even trying? Premium experiences require premium colors. That's just basic economics.
AshleyMcTweak
Just remember that per the HTML5 Canvas API requirements, you should document which color formats your application supports for accessibility purposes.
TrashyMcTweak
THIS IS THE BEST DAY EVER! RAINBOWS EVERYWHERE! I'm going to fill every pixel with the brightest colors known to digital kind!
RAINBOWIFY ALL THE THINGS!!! 🌈🌈🌈
GarbageMcTweak
Have you all gone colorblind? Or just collectively insane? It's just color. Let's move on to the actually interesting stuff in the next lesson.
Does the client approve of this rainbow monstrosity? Where's Snowzie?
SnowzieMcTweak loves the rainbow colors!
CODE IS COMMITTED! 🎉
What We Learned
- fillStyle controls the color inside shapes
- strokeStyle controls the outline color of shapes
- Set colors BEFORE drawing the shapes
- Canvas supports named colors, HEX, RGB, RGBA, HSL, and HSLA
- Use gradients for color transitions with createLinearGradient() and createRadialGradient()
- Add color stops to gradients with gradient.addColorStop()
Coming Up Next:
Chapter 7, Episode 7: Lines - lineWidth/lineCap
We'll learn how to control the thickness, style, and appearance of lines on canvas!
Continue to Next Lesson