Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I plot a gradient line in HTML canvas?

Tags:

html

canvas

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

like image 383
Nasir Avatar asked Sep 24 '11 19:09

Nasir


People also ask

How do you make a gradient on canvas HTML?

To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).

How do you make a linear gradient in HTML?

The createLinearGradient() method creates a linear gradient object. The gradient can be used to fill rectangles, circles, lines, text, etc. Tip: Use this object as the value to the strokeStyle or fillStyle properties.

How do I draw a line in canvas in HTML?

To draw a line on a canvas, you use the following steps: First, create a new line by calling the beginPath() method. Second, move the drawing cursor to the point (x,y) without drawing a line by calling the moveTo(x, y) . Finally, draw a line from the previous point to the point (x,y) by calling the lineTo(x,y) method.

Can you make gradients in HTML?

There is no special property for this; you simply use the background or background-image property and define your gradient in its value. You can create both linear and radial gradients this way.


1 Answers

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/

like image 152
Simon Sarris Avatar answered Sep 18 '22 14:09

Simon Sarris