让SVG线性渐变以特定角度填充矩形总是

让SVG线性渐变以特定角度填充矩形总是

问题描述:

我需要使用从左上角到右下角的单个线性渐变填充不同长宽比和大小的矩形,并且总是以45度角(而不仅仅是从角到角)。让SVG线性渐变以特定角度填充矩形总是

下面是代码,从角落到角落填充矩形,我如何使它在45deg?

还是一个的jsfiddle https://jsfiddle.net/45nuu6L0/

<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" width="100" height="50"> 
    <linearGradient id="gradient" gradientUnits="objectBoundingBox" x1="0" y1="0" x2="1" y2="1"> 
    <stop offset="0" style="stop-color:#000"/> 
    <stop offset="0.48" style="stop-color:#000;stop-opacity:0"/> 
    <stop offset="1" style="stop-color:#000"/> 
    </linearGradient> 
    <rect width="100%" height="100%" fill="url(#gradient)" /> 
</svg> 
+0

是不是其中任一梯度从顶部进入从左上到右下或它进入45度不同时(除了在一个正方形的情况下)的情况下? –

+1

SVG渐变不支持该行为。我不相信有什么方法可以实现你所需要的,而不用用JS动态操作SVG渐变。 –

我的事情你要和你的LinearGradient的gradientTransform性能的发挥。作为起点:

<!DOCTYPE html> <html> <body> 
 

 
<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" width="100" height="50"> 
 
    <linearGradient gradientTransform="rotate(-45)" id="gradient" gradientUnits="objectBoundingBox" x1="0" y1="0" x2="0" y2="1" > 
 
<stop offset="0" style="stop-color:#000"/> 
 
<stop offset="0.48" style="stop-color:#000;stop-opacity:0"/> 
 
<stop offset="1" style="stop-color:#000"/> 
 
    </linearGradient> 
 
    <rect width="100%" height="100%" fill="url(#gradient)" /> 
 
</svg> 
 

 
</body></html>