Change the properties of an SVG object with JS

0

I'm learning about creating SVG graphics for HTML and would like to know how to change the properties of an SVG cicle, rect) through JS for example, when you click on a button it changes the position of a line. I looked at some websites and could not find them.

Thanks in advance.

    
asked by anonymous 13.03.2018 / 06:00

1 answer

2

You can change the properties of SVG 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>
    
13.03.2018 / 12:10