【问题标题】:Javascript how to change svg linear-gradient stop-colorJavascript如何更改svg线性渐变停止颜色
【发布时间】:2021-09-09 07:44:44
【问题描述】:

.svg 中,我有一个渐变,颜色与0.2 opacity 相同。使用input color picker,我可以选择任何颜色并用它填充svg。但是如果我通过更改#linear-gradient 的两个stop-color 属性来保持透明度呢?

<linearGradient id="linear-gradient" x1="293.5" x2="293.5" y2="101" gradientUnits="userSpaceOnUse">
  <stop offset="0" stop-color="#3bf4cf"/>
  <stop offset="1" stop-color="#3bf4cf" stop-opacity="0.2"/>
</linearGradient>

我可以使用以下内容查询选择该属性吗:

document.getElementById('linear-gradient').querySelector('stop')...

或者我应该只是简单地更改 LinearGradient innerHTML?

【问题讨论】:

  • 你可以做任何一个。

标签: javascript svg


【解决方案1】:

可能是这样的:

document.forms.form01.color.addEventListener('change', e => {
  document.getElementById('stop1').attributes['stop-color'].value = e.target.value;
});
<form name="form01">
  <input type="color" name="color"/>
</form>
<svg viewBox="0 0 100 100" width="200">
  <defs>
    <linearGradient id="lg1" gradientUnits="userSpaceOnUse">
      <stop id="stop1" offset="0" stop-color="#3bf4cf"/>
      <stop id="stop2" offset="1" stop-color="#3bf4cf" stop-opacity="0.2"/>
    </linearGradient>
  </defs>
  <rect x="0" y="0" width="100" height="100" fill="url(#lg1)" />
</svg>

【讨论】:

    猜你喜欢
    • 2020-11-20
    • 2019-12-16
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    相关资源
    最近更新 更多