使用css画一个3D饼图的效果

<!DOCTYPE html>
<html>
<head>
<title>3D Pie Chart with CSS</title>
<style>
body {
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.pie-chart {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  position: relative;
  perspective: 800px; /* Creates 3D perspective */
  transform-style: preserve-3d; /* Preserves 3D transformations */
}

.slice {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  clip: rect(0, 100px, 200px, 0); /* Initial clip for half-circle */
  transform-origin: left center; /* Rotation origin */
}

.slice .half {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #eee; /* Default color for back face */
  transform: translateZ(-1px); /* Slightly offset for visibility */
}

/* Individual slice styles and rotations */
.slice:nth-child(1) {
  background-color: #f44336;
  transform: rotate(0deg); /* Starting angle */
}

.slice:nth-child(2) {
  background-color: #2196f3;
  transform: rotate(90deg); /* Accumulated angle */
  clip: rect(0, 200px, 200px, 100px); /* Adjust clip for second half */
}

.slice:nth-child(3) {
  background-color: #4caf50;
  transform: rotate(225deg); /* Accumulated angle */
  clip: rect(0, 200px, 200px, 100px);
}

.slice:nth-child(4) { /* Example of smaller slice */
  background-color: #ffeb3b;
  transform: rotate(300deg);
  clip: rect(0, 200px, 200px, 100px);
}


/* Add a 3D effect with shadows (optional) */
.pie-chart:before {
  content: '';
  position: absolute;
  width: 90%;
  height: 90%;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.1);
  top: 5%;
  left: 5%;
  z-index: -1;
  filter: blur(2px); /* Soften the shadow */
}

</style>
</head>
<body>

<div class="pie-chart">
  <div class="slice">
    <div class="half"></div>
  </div>
  <div class="slice">
    <div class="half"></div>
  </div>
  <div class="slice">
    <div class="half"></div>
  </div>
  <div class="slice">
    <div class="half"></div>
  </div>
</div>

</body>
</html>

Explanation and Key Improvements:

  • 3D Perspective: The perspective property on the .pie-chart container creates the 3D space. transform-style: preserve-3d ensures that child elements maintain their 3D transformations.
  • Slice Rotation: Each .slice is rotated using transform: rotate(angle). The angles are cumulative to create the pie effect.
  • Half-Circles and Clipping: The clip: rect() property creates the half-circle shapes. The values are adjusted for the second and subsequent slices to ensure they fit together correctly. This is a cleaner approach than using pseudo-elements.
  • Transform Origin: transform-origin: left center sets the rotation point to the left edge of the circle, which is crucial for the pie chart effect.
  • Back Face Color: The .half element inside each slice provides a consistent background color for the back face of
posted @ 2024-12-07 10:05  王铁柱6  阅读(71)  评论(0)    收藏  举报