Linear Gradient

Canvas gradients are a way of filling shapes or strokes with color transitions.

A linear gradient is created using the 2D Context function createLinearGradient(x1, y1, x2, y2). The gradient extends from the start point x1, y1 to the end point x2, y2.
Once we've created our gradient, we can insert colors using the addColorStop(position, color).
After the gradient is created and assigned to a variable, this variable can be assigned to fillStyle and strokeStyle properties.

Functions:

Linear Gradient Direction
#
  • createLinearGradient(x1, y1, x2, y2) - creates a gradient along the line given by the coordinates represented by the parameters. Note: If a gradient extends from x=10 to x=110, then only graphics drawn with x-values between 10 and 110 will have a gradient color applied to them. Graphics drawn outside this area are still affected by the gradient, but will be drawn using either the first or last color of the gradient.
  • addColorStop(position, color) - the first parameter tells how far into the gradient area this color stop is to be placed. The second parameter is the color itself. The direction of the linear gradient moves from the starting point to the ending point of the imaginary line defined with createLinearGradient(). Color stops are placed along the imaginary line between 0 and 1, where 0 is at the starting point, and 1 is at the ending point.
  • Properties:


    To Do

    Try the following options:

    1. Diagonal gradient
        var gradient = ctx.createLinearGradient(100,100,200,200);
        gradient.addColorStop(0,"#DD33CC");
        gradient.addColorStop(1,"white");
        ctx.fillStyle = gradient;
        ctx.fillRect(0,0,400,400);  
    2. Rectangles on the right side are over the gradient end
        var gradient = ctx.createLinearGradient(150, 0, 350,0);
        gradient.addColorStop(0, 'rgb(0, 0, 255)');
        gradient.addColorStop(1, 'rgb(0, 255, 0)');
      
        ctx.fillStyle = gradient;
      
        ctx.fillRect(10,10,130, 100);
        ctx.fillRect(150,10, 150, 100);
        ctx.fillRect(320,10, 80, 100);
      
        ctx.fillRect(100,120, 150, 100);
        ctx.fillRect(280,120, 150, 100);
    3. Rainbow Gradient
        var gradient = ctx.createLinearGradient(0, 0, 400, 0);
        gradient.addColorStop(0, 'red');
        gradient.addColorStop(1 / 6, 'orange');
        gradient.addColorStop(2 / 6, 'yellow');
        gradient.addColorStop(3 / 6, 'green');
        gradient.addColorStop(4 / 6, 'blue');
        gradient.addColorStop(5 / 6, 'indigo');
        gradient.addColorStop(1, 'violet');
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, 400, 75);  

    FOR FULL TABLE HEIGHT IN IFRAME