KeironLowe
KeironLowe

Reputation: 731

JS/CSS Clip Path - How to calculate radius for circle?

I'm trying to dynamically set the radius for clip-path: circle(radius) so that it fit's within whatever size container it's in (with a bit of extra space around it). For example, if the container is 1000x500, then the entire circle should be 2/3rds of 500px.

I've tried setting the radius to a simple percentage such as 33%, which should make the full circle 2/3rds but depending on the size of the container it can either be too big or too small.

Looking at the documentation for basic shapes, the percentage for radius is resolved from the width and height of the containing box, sqrt(width^2+height^2)/sqrt(2) but I have no idea how to actually use that to make the calculation.

Does anybody know what I can do? I'm animating these values so I do need it to be done via clip-path.

Upvotes: 1

Views: 481

Answers (1)

Temani Afif
Temani Afif

Reputation: 273428

You can do the same with mask and without any calculation

.box {
  display:inline-block;
  vertical-align:top;
  background:url(https://picsum.photos/id/1074/800/800) center/cover no-repeat;

  -webkit-mask:radial-gradient(circle closest-side,#fff 99%,transparent 100%);
          mask:radial-gradient(circle closest-side,#fff 99%,transparent 100%);
}
<div class="box" style="width:200px;height:100px"></div>

<div class="box" style="width:100px;height:200px"></div>

<div class="box" style="width:300px;height:300px"></div>

To illustrate how it works:

.box {
  display:inline-block;
  vertical-align:top;
  border:2px solid;
  background:
     radial-gradient(circle closest-side,transparent 99%,red 100%),
     url(https://picsum.photos/id/1074/800/800) center/cover no-repeat;
}
<div class="box" style="width:200px;height:100px"></div>

<div class="box" style="width:100px;height:200px"></div>

<div class="box" style="width:300px;height:300px"></div>


You can also add animation:

.box {
  display:inline-block;
  vertical-align:top;
  background:url(https://picsum.photos/id/1074/800/800) center/cover no-repeat;

  -webkit-mask:radial-gradient(circle closest-side,#fff 99%,transparent 100%) center/100% 100% no-repeat;
          mask:radial-gradient(circle closest-side,#fff 99%,transparent 100%) center/100% 100% no-repeat;
   transition:0.5s;
}
.box:hover {
   -webkit-mask-size:0% 0%;
           mask-size:0% 0%;
}
<div class="box" style="width:300px;height:300px"></div>
<div class="box" style="width:200px;height:100px"></div>

Upvotes: 2

Related Questions