How to get a rotated linear gradient svg for use as a background image?

前端 未结 4 1334
心在旅途
心在旅途 2021-02-05 03:44

I\'ve seen a few questions dancing around this, so I hope this isn\'t too redundant. Ideally, I\'d like an image/svg+xml which scales to 100% of it\'s container. C

相关标签:
4条回答
  • 2021-02-05 04:20

    Please note that the gradientTransform attribute rotates the gradient according to it's anchor point at 0,0. To rotate it from the 'center' you need to calculate the proper percentages for x1, y1, x2 and y2. A simple PHP example:

    // Rotation can be 0 to 360
    $pi = $rotation * (pi() / 180);
    $coords = array(
        'x1' => round(50 + sin($pi) * 50) . '%',
        'y1' => round(50 + cos($pi) * 50) . '%',
        'x2' => round(50 + sin($pi + pi()) * 50) . '%',
        'y2' => round(50 + cos($pi + pi()) * 50) . '%',
    )
    
    0 讨论(0)
  • 2021-02-05 04:22

    To rotate the gradient you can e.g use the 'gradientTransform' attribute, like this:

    <?xml version="1.0" ?>
    <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" 
     viewBox="0 0 1 1" preserveAspectRatio="none">
      <linearGradient id="grad-ucgg-generated" gradientUnits="userSpaceOnUse" 
       x1="0%" y1="0%" x2="100%" y2="0%" gradientTransform="rotate(65)">
        <stop offset="0%" stop-color="#ffffff" stop-opacity="0"/>
        <stop offset="100%" stop-color="#ff0000" stop-opacity="1"/>
      </linearGradient>
      <rect x="0" y="0" width="1" height="1" fill="url(#grad-ucgg-generated)" />
    </svg>

    0 讨论(0)
  • 2021-02-05 04:34
    <linearGradient gradientTransform="rotate(65)">
    
    0 讨论(0)
  • 2021-02-05 04:38

    Giel Berkers' solution in Javascript would be:

    // angle can be 0 to 360
    var anglePI = (angle) * (Math.PI / 180);
    var angleCoords = {
        'x1': Math.round(50 + Math.sin(anglePI) * 50) + '%',
        'y1': Math.round(50 + Math.cos(anglePI) * 50) + '%',
        'x2': Math.round(50 + Math.sin(anglePI + Math.PI) * 50) + '%',
        'y2': Math.round(50 + Math.cos(anglePI + Math.PI) * 50) + '%',
    }
    
    0 讨论(0)
提交回复
热议问题