Chapter 43: Canvas Linear Gradient

1. What is a Linear Gradient in Canvas? (Clear definition first)

A linear gradient in Canvas means a smooth color transition that changes gradually along a straight line — from one color to another (or several colors) in a specific direction.

Examples you see every day:

  • Buttons that look shiny or 3D (light color on top → dark color on bottom)
  • Backgrounds that fade from blue to purple
  • Progress bars that go from green to red
  • Sky in simple games (light blue at top → darker at bottom)
  • Metallic / plastic / glass effects

In Canvas, a linear gradient is not a single color — it’s a recipe that tells the browser:

  • Where the color change starts (point 1)
  • Where it ends (point 2)
  • What colors to use at different points along that line

2. How to Create & Use a Linear Gradient (Core Steps)

You need three main steps:

  1. Create the gradient object with createLinearGradient(x0, y0, x1, y1)
  2. Add color stops with addColorStop(offset, color)
  3. Assign it to fillStyle or strokeStyle and draw your shape

Basic syntax:

JavaScript

3. Your First Linear Gradient – Horizontal Fade (Copy-Paste & Run)

Create canvas-linear-gradient.html:

HTML

What you see:

  • Three rectangles with different gradient directions
  • Horizontal: red → yellow → blue
  • Vertical: purple → blue
  • Diagonal: green → red

4. All Important Parts of Linear Gradients (With Copy-Paste Snippets)

A. Gradient Direction (x0,y0 → x1,y1)

JavaScript

B. Multiple Color Stops (more than 2 colors)

JavaScript

C. Gradient on Stroke (Border / Line)

JavaScript

→ Thick rainbow ring

D. Semi-transparent Gradient

JavaScript

→ Top-to-bottom white fade overlay

5. Teacher’s Quick Tips (Hyderabad Student Style 😄)

  • Gradient coordinates are relative to the canvas, not the shape — so createLinearGradient(0,0,canvas.width,0) always goes full horizontal
  • Use 0 to 1 for addColorStop(offset) — 0 = start, 1 = end
  • Common mistake #1: Forget to assign gradient to fillStyle or strokeStyle → solid color instead
  • Common mistake #2: Wrong coordinates → gradient goes in unexpected direction
  • Pro tip: Use online gradient generators (like cssgradient.io) → copy colors → paste into addColorStop
  • Pro tip 2: Combine with globalAlpha or rgba for transparency effects

Understood Canvas Linear Gradient fully now? This is one of the most beautiful and most-used features in Canvas — almost every modern button, background, progress bar, card, chart, and loader uses linear gradients.

Tell me what you want next — we can build on this:

  • Full animated gradient shift (moving shine)?
  • Radial gradient (circular / orb style)?
  • Gradient on text or stroke only?
  • Glassmorphism card with gradient + blur?
  • Or 15-question linear gradient quiz?

Just say — we keep going step by step together! 🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *