Gradient Stroke Along Curve in Canvas

前端 未结 2 784
遥遥无期
遥遥无期 2020-12-03 06:02

I\'m trying to draw a curve in canvas with a linear gradient stoke style along the curve, as in this image. On that page there is a linked svg file that gives instr

2条回答
  •  时光取名叫无心
    2020-12-03 06:36

    A Demo: http://jsfiddle.net/m1erickson/4fX5D/

    It's fairly easy to create a gradient that changes along the path:

    enter image description here

    It's more difficult to create a gradient that changes across the path:

    enter image description here

    To create a gradient across the path you draw many gradient lines tangent to the path:

    enter image description here

    If you draw enough tangent lines then the eye sees the curve as a gradient across the path.

    enter image description here

    Note: Jaggies can occur on the outsides of the path-gradient. That's because the gradient is really made up of hundreds of tangent lines. But you can smooth out the jaggies by drawing a line on either side of the gradient using the appropriate colors (here the anti-jaggy lines are red on the top side and purple on the bottom side).

    Here are the steps to creating a gradient across the path:

    • Plot hundreds of points along the path.

    • Calculate the angle of the path at those points.

    • At each point, create a linear gradient and draw a gradient stroked line across the tangent of that point. Yes, you will have to create a new gradient for each point because the linear gradient must match the angle of the line tangent to that point.

    • To reduce the jaggy effect caused by drawing many individual lines, you can draw a smooth path along the top and bottom side of the gradient path to overwrite the jaggies.

    Here is annotated code:

    
    
    
     
    
           
    
    
    
        
    
    
    

提交回复
热议问题