Circle area defined by mouse click

by Génesis García Morilla

HTML

<p>Scope <span id="percent">0</span>%</p>
<div id="container" class="inside-center">
  <div id="circle"></div>
</div>

CSS

p {
  text-align: center;
  color: #2b2b2b;
  font-family: "Roboto Condensed";
  text-transform: uppercase;
}

/* Horizontal and vertical alignment for elements inside */
.inside-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

#container {
  width: 300px;
  height: 300px;
  margin: auto;
  background-color: antiquewhite;
}

#circle {
  width: 50%;
  height: 50%;
  background-color: #181818;
  opacity: 0.75;
  border-radius: 50%;
  transition: all 0.2s ease-out;
}

JavaScript

var percent = 0;

var $percent = document.querySelector("#percent");
var $circle = document.querySelector("#circle");

document.querySelector("#container").addEventListener("click", function(e) {
  var offset = this.getClientRects()[0];

  // Width and height are igual, it doesn't matter which we will set for our maths
  var width = e.currentTarget.clientWidth;
  
  // Absolute position of the mouse cursor from the circle center
  var x = Math.abs(e.clientX - offset.left - width/2);
  var y = Math.abs(e.clientY - offset.top - width/2);
  // we are in the first quadrant of a coordinate axis
  
  // The maximum will tell us the percent of the circle area
  percent = Math.round(2*Math.max(x, y)*100/width);

  $circle.style.width = percent + "%";
  $circle.style.height = percent + "%";

  $percent.textContent = percent;
});