DHRUVI ANITBHAI PATEL
DHRUVI ANITBHAI PATEL

Reputation: 29

jQuery Easing animation(want to transform rectangle to circle)

this my code and i want to transform this rectangle to circle by using jQuery.

$("#btn1").click(function(){
  $("#greenrec").animate({
    height:150,
    width:150,
    opacity: 0.6,
    borderWidth: "10px",
    marginLeft: "50px"
  }, 1000,"easeInBack");
})

Upvotes: 1

Views: 144

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

To transform the rectangle in to a circle you can animate the border-radius property to 50%, like this:

$("#btn1").click(function() {
  $("#greenrec").animate({
    height: 150,
    width: 150,
    opacity: 0.6,
    borderWidth: "10px",
    marginLeft: "50px",
    borderRadius: '50%'
  }, 1000, "easeInBack");
})
#greenrec {
  width: 150px;
  height: 150px;
  background-color: #0C0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js" integrity="sha512-0QbL0ph8Tc8g5bLhfVzSqxe9GERORsKhIn1IrpxDAgUsbBGz/V7iSav2zzW325XGd1OMLdL4UiqRJj702IeqnQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<button id="btn1">Change</button>

<div id="greenrec"></div>

One thing to note when performing animations is that JS is not very performant. Where possible you should look to use CSS for animating elements as it's hardware accelerated. I'd suggest using the following approach, where you simply use JS to set a class on the element and CSS performs the animation:

$("#btn1").click(function() {
  $("#greenrec").toggleClass('circle');
})
#greenrec {
  width: 150px;
  height: 150px;
  background-color: #0C0;
  transition-property: margin, opacity, border-radius;
  transition-duration: 1s;
  transition-timing-function: cubic-bezier(0.36, 0, 0.66, -0.56); /* easeInBack */
}

.circle {
  opacity: 0.6;
  margin-left: 50px;
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1">Change</button>

<div id="greenrec"></div>

Upvotes: 2

Related Questions