Javascript DOM <SVG> Set circle size

Description

Javascript DOM <SVG> Set circle size

View in separate window

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Using Math method to fit a circle</title>
<style type="text/css">
#elem {/*from  w ww.jav  a  2s. co  m*/
  width: 400px;
  height: 200px;
  border: 1px solid #000;
}
</style>
<script type="text/javascript">
  function compStyle(elemId, property) {
    let elem = document.getElementById(elemId);
    let style;
    if (window.getComputedStyle)
      style = window.getComputedStyle(elem, null).getPropertyValue(
          property);
    else if (elem.currentStyle)
      style = elem.currentStyle[property];
    return style;
  }
  window.onload = function() {
    let height = parseInt(compStyle("elem", "height"));
    let width = parseInt(compStyle("elem", "width"));

    let x = width / 2;
    let y = height / 2;

    let circleRadius = Math.min(width, height) / 2;

    let circ = document.getElementById("circ");
    circ.setAttribute("r", circleRadius);
    circ.setAttribute("cx", x);
    circ.setAttribute("cy", y);
  }
</script>

</head>
<body>
  <div id="elem">
    <svg xmlns="http://www.w3.org/2000/svg" width="600" height="600">
<circle id="circ" width="10" height="10" r="10" fill="red" />
</svg>
  </div>
</body>
</html>



PreviousNext

Related