Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

CSS Animation: Vẽ tròn có viền (border-radius) nền trong suốt

Tạo hiệu ứng vẽ tròn (stroke animation) chỉ bằng CSS, không dùng SVG hay Canvas. Kỹ thuật dùng clip-path hoặc che phủ (masking) kết hợp animation xoay.

CSS hoàn chỉnh

body {
  background: repeating-linear-gradient(45deg, white 0px, green 100px);
  height: 400px;
  background-size: 400px 400px;
  background-repeat: no-repeat;
}
html { height: 100%; }

#box {
  position: absolute;
  width: 400px;
  height: 400px;
  border: solid blue 2px;
  animation: colors 5s infinite;
}

#demo {
  width: 50%;
  height: 100%;
  right: 0;
  position: absolute;
  overflow: hidden;
  transform-origin: left center;
  animation: cliprotate 18s steps(2) infinite;
  -webkit-animation: cliprotate 18s steps(2) infinite;
}

.circlehalf {
  box-sizing: border-box;
  height: 100%;
  right: 0;
  position: absolute;
  border: solid 20px transparent;
  border-top-color: blue;
  border-left-color: blue;
  border-radius: 50%;
}

#clipped {
  width: 200%;
  animation: rotate 8s linear infinite;
  -webkit-animation: rotate 8s linear infinite;
}

#fixed {
  width: 100%;
  transform: rotate(145deg);
  animation: showfixed 18s steps(2) infinite;
  -webkit-animation: showfixed 18s linear infinite;
}

@-webkit-keyframes cliprotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
@keyframes cliprotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
@-webkit-keyframes rotate {
  0% { transform: rotate(-45deg); }
  100% { transform: rotate(135deg); }
}
@keyframes rotate {
  0% { transform: rotate(-45deg); }
  100% { transform: rotate(135deg); }
}
@-webkit-keyframes showfixed {
  0% { opacity: 0; }
  49.9% { opacity: 0; }
  50% { opacity: 1; }
  100% { opacity: 1; }
}

HTML

<div id="box">
  <div id="demo">
    <div class="circlehalf" id="clipped"></div>
  </div>
  <div class="circlehalf" id="fixed"></div>
</div>

Nguyên lý hoạt động

  • .circlehalf: Nửa vòng tròn (border-top + border-left + border-radius: 50%).
  • #demo: Container nửa trái, overflow: hidden, xoay liên tục (cliprotate) để "quét" nửa tròn.
  • #clipped: Nửa tròn bên trong, xoay ngược (rotate) để vẽ nét.
  • #fixed: Nửa tròn cố định, hiện/ẩn xen kẽ (showfixed) để hoàn thành vòng tròn.
  • steps(2): Chia animation thành 2 bước gắt (không mượt) để tạo hiệu ứng vẽ đoạn.

Kỹ thuật này phức tạp; hiện nay khuyên dùng SVG stroke-dasharray animation hoặc Canvas cho hiệu ứng vẽ tròn đơn giản, dễ bảo trì hơn.