Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate rotation of canvas gradient

Tags:

People also ask

How do you rotate a path in canvas?

Choose the Rotate tool to rotate path points around a reference point. To rotate one or more path points, first select the path points using the Path Selection tool. With the Rotate tool active, click and drag anywhere on the canvas to rotate the path points clockwise or counterclockwise.

How do you make a gradient on a canvas?

The addColorStop() method specifies the color stops, and its position along the gradient. Gradient positions can be anywhere between 0 to 1. To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the shape (rectangle, text, or a line).

How do I rotate a shape in HTML canvas?

To rotate a shape around its own center, you must first translate the canvas to the center of the shape, then rotate the canvas, then translate the canvas back to 0,0, and then draw the shape. This example first translates (moves) the center of the canvas to the center of the square (cx, cy).

How do you rotate in JavaScript?

To rotate an image with JavaScript, access the image element with a method like getElementById() , then set the style. transform property to a string in the format rotate({value}deg) , where {value} is the clockwise angle of rotation in degrees.


I'm trying to use a gradient to fill an area of a canvas, but I would like to be able to set the angle of the gradient.

I know this is possible by using different values in the creation of the gradient (ctx.createLinearGradient(x1, y1, x2, y2)) as seen here:

Gradient creation graphic

But I can't seem to get my head around the maths needed to convert an angle (radians) to a gradient size that will produce the same angle (The angle I'm referring to is perpendicular to the direction of the gradient, so a 0 radian angle would show the gradient on the right)

In short, how can I convert (quantity) of radians into an X by Y shape?

$(document).ready(function(){
    var canvas = document.getElementById("test");
    var ctx = canvas.getContext("2d");
    var angle = 0.5;
    
    ctx.beginPath();
    ctx.moveTo(100, 100);
    ctx.arc(100, 100, 100, 0, -angle, true);
    ctx.lineTo(100, 100);
    ctx.closePath();

    // Convert angle into coordinates to tilt the grad
    // grad should be perpendicular to the top edge of the arc
    var grad = ctx.createLinearGradient(0, 0, 0, 100);
    
    grad.addColorStop(0, "rgba(0,0,0,0)");
    grad.addColorStop(1, "rgba(0,0,0,0.8)");
    ctx.fillStyle = grad;
    ctx.fill();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="test" width="500" height="500"></canvas>

(So no one wastes their time: I specifically don't want to use a context.rotate() in this case)