Canvas Text Gradients for Backgrounds and Strokes

Text gradients are super easy to achieve with HTML5 Canvas.

Process

Here’s the process:

Step 1

Create your CanvasGradient object with createLinearGradient.

[js]
// createLinearGradient(start_x, start_y, end_x, end_y);
var grad = ctx.createLinearGradient(50, 20, 220, 70);
[/js]

Step 2

Add your Gradient Color Stops.

[js]
grad.addColorStop(0, ‘red’);
grad.addColorStop(0.3, ‘yellow’);
grad.addColorStop(0.5, ‘green’);
grad.addColorStop(0.8, ‘deepPink’);
grad.addColorStop(1, ‘blue’);
[/js]

Step 3

Set your fillStyle or strokeStyle.

[js]
ctx.fillStyle = grad;
// or ctx.strokeStyle = grad;
[/js]

Step 4

Finally, draw your text with fillText or strokeText.

[js]
// Setting the BaseLine
ctx.textBaseline = ‘top’;
// Setting Font details
ctx.font = ‘bold 40px Verdana’;
// Drawing the text
ctx.fillText(‘CSSDeck’, 50, 20);
// or ctx.strokeText(‘CSSDeck’, 50, 20);
[/js]

Step 5

Here’s your Demo.

Quick Tip

Try altering the arguments that you passed to ctx.createLinearGradient(). Tweaking them will allow you to change the gradient directions!

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.