Search code examples
javascriptreactjscanvaskonvajs

Unable to give gradient to a line using react-konva


I have used react-konva to draw a line. Now, I am trying to give that line a gradient but it's not working for me. Here is the relevant code:

            <Layer>
                <Motion
                    style={
                        {
                            startX: spring(100),
                            startY: spring(100),
                            endX: spring(!isLineScale ? 500 : 100),
                            endY: spring(!isLineScale ? 500 : 100),
                        }
                    }
                >
                    {({startX, startY, endX, endY}) => {
                        return(
                            <Line
                                points={[startX, startY, endX, endY]}
                                stroke={stroke}
                                strokeWidth={5}
                                fillLinearGradientStartPointX={100}
                                fillLinearGradientStartPointY={100}
                                fillLinearGradientEndPointX={500}
                                fillLinearGradientEndPointY={500}
                                fillLinearGradientColorStops={[0, 'green', 0.5, 'red']}
                            />
                        )
                    }}
                </Motion>
            </Layer>

Solution

  • react-konva has no support for gradient stroke via configuration. But you can create gradient manually, and then use as stroke property.

    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    var gradient = ctx.createLinearGradient(0, 0, 100, 100);
    gradient.addColorStop(0.00, 'red');
    gradient.addColorStop(1 / 6, 'orange');
    gradient.addColorStop(2 / 6, 'yellow');
    gradient.addColorStop(3 / 6, 'green')
    gradient.addColorStop(4 / 6, 'aqua');
    gradient.addColorStop(5 / 6, 'blue');
    gradient.addColorStop(1.00, 'purple');
    
    function App() {
        return (
          <Stage width={700} height={700}>
            <Layer>
                <Line points={[50, 50, 200, 200]} stroke={gradient} />
            </Layer>
          </Stage>
        );
    }
    

    Demo: http://jsbin.com/hohoyuliro/edit?js,output