Artemis
Artemis

Reputation: 599

Javascript how to change svg linear-gradient stop-color

In an .svg I have a gradient with a color to the same color with 0.2 opacity. With an input color picker I can select any color and fill the svg with that. But what if I would keep the transparency by changing the two stop-color properties of #linear-gradient?

<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>

can I query select that property with something like:

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

or should I just simply change LinearGradient innerHTML?

Upvotes: 0

Views: 883

Answers (1)

chrwahl
chrwahl

Reputation: 13060

Could be something like this:

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>

Upvotes: 1

Related Questions