Center color gradient of Canvas html5

0

I have the following gradient on canvas.

link

My question is: Why, if I set the red to 0.5, does it appear in the middle of the bar?

How do I get my color to appear right in the center? How does the gradient system work?

LOOK AT COMPLETE SCREEN

function fade() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var gradient = canvas.getContext("2d").createLinearGradient(0, 0, 1, 500);

    gradient.addColorStop(0, 'gray');
    gradient.addColorStop(0.5, 'red');
        gradient.addColorStop(0.6, 'red');
    gradient.addColorStop(1.0, 'gray');

    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, 200, 800);
}

fade();
<canvas id="canvas" width="200px" height="800"></canvas>
    
asked by nawelittle 29.05.2017 в 17:25
source

1 answer

1

The problem is the coordinates you indicated when creating the gradient .

The parameters that createLinearGradient receive are:

  

CanvasGradient ctx.createLinearGradient(x0, y0, x1, y1);

     

Where:
x0 : The axis x of the start point coordinate.
y0 : The axis y of the start point coordinate.
x1 : The axis x of the coordinate of the end point.
y1 : The axis y of the coordinate of the end point.

That is, if the canvas measures 800px and you want the red one to be exactly in the middle you can do 2 things:

  • OP1: Indicate that gradient go to 800px ( eg: y1 = 800 )
  • OP2 : Indicate that gradient starts at 300px ( eg: y0 = 300 ), which is exactly the same distance from the end of gradient to the lower edge of canvas

Example using OP1

function fade() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var gradient = canvas.getContext("2d").createLinearGradient(0, 0, 1, 800);

    gradient.addColorStop(0, 'gray');
    gradient.addColorStop(0.5, 'red');
        gradient.addColorStop(0.6, 'red');
    gradient.addColorStop(1.0, 'gray');

    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, 200, 800);
}

fade();
<canvas id="canvas" width="200px" height="800"></canvas>
    
answered by 29.05.2017 в 18:08