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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With