如何将 svg 中的线性渐变作为 div 的背景颜色?

How to give the linear-gradient in svg as a background color for a div?

我有一个 svg 像

<svg>
    <linearGradient id="SVGID_124_" gradientUnits="userSpaceOnUse" x1="205.2935" y1="707.9475" x2="206.9863" y2="707.9475" gradientTransform="matrix(41.432 0 0 -41.432 -8114.9512 30139.9746)">
      <stop  offset="0" style="stop-color:#0071BC"/>
      <stop  offset="3.780070e-02" style="stop-color:#0071BC"/>
      <stop  offset="0.6151" style="stop-color:#00538B"/>
      <stop  offset="0.784" style="stop-color:#004C86"/>
      <stop  offset="0.9966" style="stop-color:#003B7C"/>
      <stop  offset="1" style="stop-color:#003B7C"/>
    </linearGradient>
</svg>

我不确定如何将此线性渐变作为按钮的背景。我尝试了以下方法,但我不知道如何在 css.

中进行渐变变换

.btn {
  background: linear-gradient(to right, #0071BC 0%, #0071BC 37.80070%, #00538B 061.51%, #004C86 078.4%, #003B7C 099.66%, #003B7C 100%);
  color: white;
  border-radius: 8px;
  /* border: 1px solid #00538B; */
  width: 95%;
  height: 25px;
  padding: 0px;
}
<button class="btn">button</button>

有人可以帮忙吗? 预计看起来像这样

但我得到的是:

这是 css 中的密梯度。

.btn {
  background: linear-gradient(to right, #0071bd 0%,#0171bb 39%,#016db5 41%,#005691 58%,#005691 59%,#01538b 61%,#014c86 78%,#003c7b 100%);
  
  border-radius: 5px;
  color: #fff;
  border: none;
}
<button class="btn">Closed</button>

通常,我使用 gradient editor by colorzila 从图像 / css / 手动生成渐变。请问还有别的工具吗

您可以使用 SVG 本身,但是:

  1. 你必须确保渐变的坐标是正确的,并且是元素的脚(又名 .btn),在这种情况下,不是。
  2. 您需要将其转换为base64。

在下面的代码片段中,为了快速修复,我创建了一个脚本来读取 html 中的 svg 并将其转换为 base64,以便您可以使用它调整渐变。

此外,我对 SVG 语法做了一些改动,请看:

const svg = document.querySelector('svg').outerHTML;
const base64 = window.btoa(svg);

document.querySelector('.btn').style.backgroundImage = `url(data:image/svg+xml;base64,${base64})`;
.btn {
  background: top repeat-x;
  background-size: cover;
  
  border-radius: 5px;
  color: #fff;
  border: none;
}
<button class="btn">Closed</button>

<svg width="1000px" height="30000px" xmlns="http://www.w3.org/2000/svg" style="display: none">
    <linearGradient id="SVGID_124_" gradientUnits="userSpaceOnUse" x1="205.2935" y1="707.9475" x2="206.9863" y2="707.9475" gradientTransform="matrix(41.432 0 0 -41.432 -8114.9512 30139.9746)">
      <stop  offset="0" style="stop-color:#0071BC"/>
      <stop  offset="3.780070e-02" style="stop-color:#0071BC"/>
      <stop  offset="0.6151" style="stop-color:#00538B"/>
      <stop  offset="0.784" style="stop-color:#004C86"/>
      <stop  offset="0.9966" style="stop-color:#003B7C"/>
      <stop  offset="1" style="stop-color:#003B7C"/>
    </linearGradient>
    <g>
  <rect fill="url(#SVGID_124_)" stroke-width="0" x="0" y="0" width="100%" height="100%" />
 </g>
</svg>