How to control the position of a SVG element with Javascript?

Viewed 135

How does one control the position of an SVG element with the coordinates generated by Javascript?

This is my attempt:

function F1() {
  L = document.getElementById("L").innerHTML = Math.floor(Math.random() * 10 + 1);
  document.getElementById("c1").cx = L * 15;
  document.getElementById("c1").cy = L * 10;
  document.getElementById("c1").r = L * 0.5;
}
svg {
  position: absolute;
}
<button onclick="F1()" id="b1"> New </button>
<label id="L"></label>
<svg>
   <circle id="c1" cx="50" cy="50" r="10"/>
 </svg>

1 Answers

Use method setAttribute().

function F1() {
  L = document.getElementById("L").innerHTML = Math.floor(Math.random() * 10 + 1);
  document.getElementById("c1").setAttribute("cx", L * 15);
  document.getElementById("c1").setAttribute("cy", L * 10);
  document.getElementById("c1").setAttribute("r", L * 0.5);
}
svg {
  position: absolute;
}
<button onclick="F1()" id="b1"> New </button>
<label id="L"></label>
<svg>
   <circle id="c1" cx="50" cy="50" r="10"/>
 </svg>

Related