Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate SVG Linear Gradient attribute x1 y1 x2 y2 if we know angle?

As we know in SVG the angular linear gradient is via setting the attribute x1,x2,y1,y2. However, If we only get the angle,

1.how to calculate the result of x1,y1,x2,y2?

2.is it correct for this formula tan (angle ) = (y2-y1)/(x2-x1)? how can I calculate the all the parameters.

like image 678
Bit Core Avatar asked Dec 09 '22 10:12

Bit Core


1 Answers

building off of JT-'s answer, here is a function that will do exactly what you need in Javascript. Just call this function passing the element and degrees as an integer. I've also added "left","right","up","down" as optional arguments.

function svg_linear_gradient_direction(element, direction){

    if(direction === "left"){

        element.setAttributeNS(null, "x1", "100%");
        element.setAttributeNS(null, "y1", "0%");
        element.setAttributeNS(null, "x2", "0%");
        element.setAttributeNS(null, "y2", "0%");

    } else if(direction === "right"){

        element.setAttributeNS(null, "x1", "0%");
        element.setAttributeNS(null, "y1", "0%");
        element.setAttributeNS(null, "x2", "100%");
        element.setAttributeNS(null, "y2", "0%");

    } else if(direction === "down"){

        element.setAttributeNS(null, "x1", "0%");
        element.setAttributeNS(null, "y1", "0%");
        element.setAttributeNS(null, "x2", "0%");
        element.setAttributeNS(null, "y2", "100%");

    } else if(direction === "up"){

        element.setAttributeNS(null, "x1", "0%");
        element.setAttributeNS(null, "y1", "100%");
        element.setAttributeNS(null, "x2", "0%");
        element.setAttributeNS(null, "y2", "0%");

    } else if(typeof direction === "number"){

        var pointOfAngle = function(a) {
            return {
                x:Math.cos(a),
                y:Math.sin(a)
            };
        }

        var degreesToRadians = function(d) {
            return ((d * Math.PI) / 180);
        }

        var eps = Math.pow(2, -52);
        var angle = (direction % 360);
        var startPoint = pointOfAngle(degreesToRadians(180 - angle));
        var endPoint = pointOfAngle(degreesToRadians(360 - angle));

        if(startPoint.x <= 0 || Math.abs(startPoint.x) <= eps)
            startPoint.x = 0;

        if(startPoint.y <= 0 || Math.abs(startPoint.y) <= eps)
            startPoint.y = 0;

        if(endPoint.x <= 0 || Math.abs(endPoint.x) <= eps)
            endPoint.x = 0;

        if(endPoint.y <= 0 || Math.abs(endPoint.y) <= eps)
            endPoint.y = 0;

        element.setAttributeNS(null, "x1", startPoint.x);
        element.setAttributeNS(null, "y1", startPoint.y);
        element.setAttributeNS(null, "x2", endPoint.x);
        element.setAttributeNS(null, "y2", endPoint.y);
    }
}
like image 177
higginsrob Avatar answered Dec 27 '22 04:12

higginsrob