gpt4 book ai didi

svg - 如果我们知道角度,计算SVG线性渐变属性x1 y1 x2 y2?

转载 作者:行者123 更新时间:2023-12-04 19:59:41 25 4
gpt4 key购买 nike

正如我们在 SVG 中所知,角度线性渐变是通过设置属性 x1,x2,y1,y2 来实现的。但是,如果我们只得到角度,

1.如何计算x1,y1,x2,y2的结果?

2. 这个公式是否正确 tan (angle ) = (y2-y1)/(x2-x1)?我如何计算所有参数。

最佳答案

基于 JT- 的答案,这里有一个函数可以完全满足您在 Javascript 中的需求。只需调用此函数,将元素和度数作为整数传递即可。我还添加了“左”、“右”、“上”、“下”作为可选参数。

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

关于svg - 如果我们知道角度,计算SVG线性渐变属性x1 y1 x2 y2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5287954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com