HTML5 Canvas
Handling Colors, Strokes, and Fills
In this chapter, we will learn to work with colors, stroke styles, and fills in the canvas
. These aspects will allow us to customize the design and appearance of graphics in our game, giving it a unique visual touch.
Applying Colors on the Canvas
To set the fill color of a shape, we use the fillStyle
property of the 2D context. fillStyle
accepts any valid CSS color value, such as color names, hexadecimal values, or the rgba
format to add transparency.
javascript
You can experiment by changing the fillStyle
value to explore different colors.
Strokes: Changing Color and Width
Besides fill color, we can customize the stroke color and style of a shape using the strokeStyle
property. We can also modify the stroke thickness with lineWidth
.
javascript
Fills and Transparency with rgba
The rgba
function allows adding transparency to colors. The last value in rgba
represents opacity, where 1 is fully opaque, and 0 is fully transparent.
javascript
Transparency is useful for creating subtle visual effects, such as shadows or layers.
Gradients in Canvas
Gradients allow smooth color transitions in a shape. In the canvas
, there are two types of gradients: linear and radial. Let's start with a linear gradient.
Linear Gradients
To create a linear gradient, we use the createLinearGradient
method, specifying the start and end of the gradient. Then, we add colors using addColorStop
.
javascript
Radial Gradients
Radial gradients create a color transition that emanates from a central point outward. This type of gradient is ideal for simulating lighting or shine effects.
javascript
Exercise: Exploring Colors and Gradients
To practice what you've learned, try creating several rectangles on your canvas
, each with a different color. Use at least one color with transparency and try both linear and radial gradients to explore possible visual effects.
javascript
Conclusion
In this chapter, we've seen how to apply colors, stroke styles, and gradients in the canvas
, which is key to customizing the graphic design of our game. These techniques enhance the appearance of our shapes and allow us to make the game visually appealing. In the next chapter, we'll learn to work with text in the canvas
, adding text elements to the game and customizing them to our needs. See you in the next chapter!
- Introducción a HTML Canvas
- Handling Colors, Strokes, and Fills
- Adding Text to the Canvas
- Capturing User Input
- Handling Images and Sprites in Canvas
- Object Animation in Canvas
- Detección de Colisiones y Lógica de Juego
- Building Game Logic
- Adding Sound Effects and Music
- Enhancing User Interactivity and Visual Experience
- Adding a HUD and Scoreboard
- Optimización del Rendimiento y Compatibilidad del Juego
- Completion and Game Testing
- Game Publishing
- Complete Project – Building the Full Game
- Next Steps