Change the properties of an SVG object with JS

Asked

Viewed 327 times

0

I’m learning about graphic creation SVG for HTML and would like to know how I can change the properties of an object SVG (line, cicle, rect) through JS for example, by clicking on a button it change the position of a line. I searched on some websites and did not find.

From now on, thank you.

1 answer

3


You can change the SVG properties with Javascript by changing the attributes with setAttribute:

function alterarSvg(){
   var svg_line = document.querySelector("#meusvg line"); // seleciono o line do SVG

   svg_line.setAttribute("x2","10"); // muda posição x2
   svg_line.setAttribute("stroke","blue"); // muda a cor para azul
}
<svg id="meusvg" width="100" height="100">
   <line x1="10" y1="10" x2="100" y2="100" stroke="green" stroke-width="4" />
</svg>
<br />
<button type="button" onclick="alterarSvg()">Clique-me</button>

  • Dude I had a supplementary question to this, if I use <text> I can change the text of this space with JS ? just as I can change the text of a <p> with DOM

  • You can. Same thing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.