如何旋转线性渐变?

时间:2016-06-07 01:41:17

标签: javascript html5 canvas

如何使我的白线从我的底部矩形的点到点完美对角线?

https://jsfiddle.net/a7rs5qu5/

  <canvas id="canvas" width="300" height="300"></canvas>

_canvas = document.getElementById('canvas');
_stage = _canvas.getContext('2d');

_stage.fillStyle = "#00FF00";
_stage.fillRect(0, 0, 300, 200);

var gradient = _stage.createLinearGradient(0, 200, 300, 300);
gradient.addColorStop(0, "blue");
gradient.addColorStop(.5, "white");
gradient.addColorStop(1, "blue");

_stage.fillStyle = gradient;
_stage.fillRect(0, 200, 300, 300);

2 个答案:

答案 0 :(得分:6)

通过数学,改变渐变坐标。您需要设置渐变坐标,以便它们描述与其正交的直线。

_canvas = document.getElementById('canvas');
_stage = _canvas.getContext('2d');

_stage.fillStyle = "#00FF00";
_stage.fillRect(0, 0, 300, 200);

var radius = 100;
var angle = Math.atan2(100, 300) + Math.PI / 2;
var gx = radius * Math.cos(angle);
var gy = radius * Math.sin(angle);
var cx = (0 + 300) / 2;
var cy = (200 + 300) / 2;

var gradient = _stage.createLinearGradient(cx - gx, cy - gy, cx + gx, cy + gy);
gradient.addColorStop(0, "blue");
gradient.addColorStop(.5, "white");
gradient.addColorStop(1, "blue");

_stage.fillStyle = gradient;
_stage.fillRect(0, 200, 300, 300);
<canvas id="canvas" width="300" height="300"></canvas>

选择radius可控制渐变的宽度;上述值仅给出与上述代码中使用的值类似的值。

答案 1 :(得分:0)

这是懒惰的更通用的解决方案。

    function createDiagonalGradient(startx, starty, endx, endy)
    {

    var height = endy - starty; 

    var radius = height; 

//-1 or 1 depending on which diagonal you want
    var angle = -1 * Math.atan2(height, endx) + Math.PI / 2;


    var gx = radius * Math.cos(angle);
    var gy = radius * Math.sin(angle);
    var cx = (startx + endx) / 2;
    var cy = (starty + endy) / 2;

    var gradient = _stage.createLinearGradient(cx - gx, cy - gy, cx + gx, cy + gy);
    gradient.addColorStop(0, "black");
    gradient.addColorStop(.5, "white");
    gradient.addColorStop(1, "black");

    return gradient; 


    }