HTML Canvas gradient only show one color

前端 未结 1 1577
清酒与你
清酒与你 2021-01-28 02:05

I\'m having problems with Canvas gradient it only shows the last color that I set on gradient.__addColorStop__(offset,color) method.

For ex

相关标签:
1条回答
  • 2021-01-28 03:05

    CanvasGradients are relative to the context's transformation matrix, not to the shape you'll fill it with.

    So in your example, since you are drawing an horizontal gradient, you set this gradient only in an area that goes from x:10 to x:200. Pixels before x:10 will have the value at index 0, and the ones after x:200 the one at index 1.
    Since you are drawing your circle at 300,150 with a radius of 50, the minimal x position your circle will attain is 250, which is after your gradient index:1 and hence solid red.

    Here is a visual demo of what happens:

    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    let gradient = ctx.createLinearGradient(10, 90, 200, 90);
    gradient.addColorStop(1 / 10, "black");
    gradient.addColorStop(1 / 5, "yellow");
    gradient.addColorStop(1 / 1, "red");
    
    // draw a full rectangle to see how the gradient is actually rendered
    ctx.fillStyle = gradient;
    ctx.fillRect(0,0,canvas.width,canvas.height);
    
    ctx.beginPath();
    ctx.arc(300, 150, 50, 0, Math.PI*2);
    ctx.strokeStyle = 'white';
    ctx.stroke();
    <canvas id="canvas" width="500" height="300"></canvas>

    To circumvent this, you have two ways:

    • generate your CanvasGradient at the correct coordinates:

    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    // x1 & x2 are set to match the circle's position
    let gradient = ctx.createLinearGradient(250, 90, 350, 90);
    gradient.addColorStop(1 / 10, "black");
    gradient.addColorStop(1 / 5, "yellow");
    gradient.addColorStop(1 / 1, "red");
    
    ctx.fillStyle = gradient;
    
    ctx.beginPath();
    ctx.arc(300, 150, 50, 0, Math.PI*2);
    ctx.fill();
    <canvas id="canvas" width="500" height="300"></canvas>

    • modify the context's transformation matrix to move your CanvasGradient:

    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    let gradient = ctx.createLinearGradient(10, 90, 200, 90);
    gradient.addColorStop(1 / 10, "black");
    gradient.addColorStop(1 / 5, "yellow");
    gradient.addColorStop(1 / 1, "red");
    
    ctx.fillStyle = gradient;
    
    ctx.beginPath();
    ctx.arc(300, 150, 50, 0, Math.PI*2);
    // our arc has been defined at the correct position
    // we can now translate the context matrix so that only the fillStyle be moved
    ctx.translate(230, 0);
    ctx.fill();
    
    // reset the default tranform matrix
    ctx.setTransform(1,0,0,1,0,0);
    <canvas id="canvas" width="500" height="300"></canvas>

    0 讨论(0)
提交回复
热议问题