Nasir
Nasir

Reputation: 2122

How can I plot a gradient line in HTML canvas?

I am trying to draw a line which is a gradient. How is that possible in canvas?

Upvotes: 31

Views: 24007

Answers (1)

Simon Sarris
Simon Sarris

Reputation: 63812

Yes. Example:

// linear gradient from start to end of line
var grad= ctx.createLinearGradient(50, 50, 150, 150);
grad.addColorStop(0, "red");
grad.addColorStop(1, "green");

ctx.strokeStyle = grad;

ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineTo(150,150);

ctx.stroke();

See it in action here:

http://jsfiddle.net/9bMPD/

Upvotes: 54

Related Questions