Canvas Text Gradients for Backgrounds and Strokes

Text gradients are super easy to achieve with HTML5 Canvas.


Here’s the process:

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Step 1

Create your CanvasGradient object with createLinearGradient.

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

Step 2

Add your Gradient Color Stops.

grad.addColorStop(0, 'red');
grad.addColorStop(0.3, 'yellow');
grad.addColorStop(0.5, 'green');
grad.addColorStop(0.8, 'deepPink');
grad.addColorStop(1, 'blue');

Step 3

Set your fillStyle or strokeStyle.

ctx.fillStyle = grad;
// or ctx.strokeStyle = grad;

Step 4

Finally, draw your text with fillText or strokeText.

// 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);

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

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

Leave a Reply

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