Patrick - 1 year ago 151
Javascript Question

How can I rotate a linear gradient?

How can I make my white line go perfectly diagonal from point to point of my bottom rectangle?

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);

_stage.fillRect(0, 200, 300, 300);
``````

By mathematics, and changing gradient coordinates. You need to set gradient coordinates so they describe a line orthogonal to it.

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

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

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);
``<canvas id="canvas" width="300" height="300"></canvas>``
The selection of `radius` controls how wide the gradient is; the above value merely gives values similar to the ones used in the code above.