How to Add Color to Canvas in HTML5 with JavaScript
To add color to a
canvas in HTML, use JavaScript to set the fillStyle property of the canvas context to a color value, then draw a shape like a rectangle with fillRect. This fills the specified area with the chosen color on the canvas.Syntax
To add color on a canvas, you first get the 2D drawing context from the canvas element. Then you set the fillStyle property to a color string (like a color name, hex, or rgb). Finally, you use fillRect(x, y, width, height) to draw a filled rectangle with that color.
canvas.getContext('2d'): gets the drawing contextcontext.fillStyle = 'color': sets the fill colorcontext.fillRect(x, y, width, height): draws a filled rectangle
javascript
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 100, 50);
Example
This example shows how to fill the entire canvas with a blue color using fillStyle and fillRect. It creates a canvas 200x100 pixels and colors it blue.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Canvas Color Example</title> </head> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'blue'; ctx.fillRect(0, 0, canvas.width, canvas.height); </script> </body> </html>
Output
A 200x100 pixel rectangle filled entirely with blue color inside a black border.
Common Pitfalls
Common mistakes when adding color to canvas include:
- Not getting the 2D context before drawing, so
fillStyleandfillRectwon't work. - Setting
fillStyleafter drawing commands, which means the color won't apply. - Using invalid color strings that the browser can't understand.
- Forgetting to specify the canvas size, which can cause unexpected scaling.
javascript
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, 100, 50); // No fillStyle set, default is black ctx.fillStyle = 'green'; ctx.fillRect(0, 60, 100, 50); // This rectangle will be green // Correct order: ctx.fillStyle = 'red'; ctx.fillRect(110, 0, 100, 50);
Quick Reference
Summary tips for adding color to canvas:
- Always get the 2D context:
canvas.getContext('2d') - Set
fillStylebefore drawing shapes - Use valid CSS color values (names, hex, rgb, rgba)
- Use
fillRectto draw colored rectangles - Clear or resize canvas carefully to avoid losing drawings
Key Takeaways
Use the 2D context's fillStyle property to set the color before drawing.
Draw colored shapes with fillRect(x, y, width, height) to add color to canvas.
Always get the canvas context first with getContext('2d').
Set fillStyle before calling fillRect to ensure the color applies.
Use valid CSS color formats like named colors, hex codes, or rgb values.