Home >Web Front-end >CSS Tutorial >How to create perfect CSS circle sectors

How to create perfect CSS circle sectors

Barbara Streisand
Barbara StreisandOriginal
2025-01-11 14:04:46698browse

Recently, I built a CSS jackpot roulette, a project that presented a unique challenge: dynamically highlighting sectors as a needle pointed to them. The roulette needed responsiveness and variable sector counts, ruling out simple image or SVG solutions. Geometric calculations were essential.

My approach involved rotating spans around a circle's center and clipping them along the radius. The initial setup, detailed below (and available in full via the link further down), involved basic styling and incremental rotation of spans (360/sectors.length degrees). It wasn't visually sophisticated at this stage.

To highlight a sector, I needed the distance between two points on a circle, given radius and angle. The formula is:

<code>2 * radius * Math.sin(θ / 2)</code>

where θ is the angle in radians. Converted for use:

<code>2 * radius * Math.sin(Math.PI / sectors.length)</code>

Next, I tackled sector clipping to prevent overlap. My first attempt used a diagonal clip-path:

<code>clip-path: polygon(100% 0, 0 50%, 100% 100%);</code>

This worked adequately with many sectors, but flaws became apparent with fewer sectors, particularly with only three, as shown:

How to create perfect CSS circle sectors

The solution involved calculating the intersection point between the span and the circle, clipping from that point to the center. This corrected the clipping:

How to create perfect CSS circle sectors

Research yielded formulas for the segments created on a horizontal ray by the line connecting intersection points:

Center segment:

<code>radius * (1 - Math.cos(θ / 2))</code>

Outer segment:

<code>radius * Math.cos(θ / 2)</code>

(θ in radians)

The ratio between these segments determines the clipping point, leading to:

<code>const clipPosition = Math.cos(Math.PI / sectors.length) * 100</code>

The corrected clip-path:

<code>{
  'clip-path': `polygon(100% 0, ${clipPosition}% 0, 0 50%, ${
    clipPosition
  }% 100%, 100% 100%)`
}</code>

The final, Vue-based result allows random spins via center clicks and targeted spins via sector clicks. (Link to the complete code omitted, as per original text). This project provided a valuable lesson in practical trigonometry.

The above is the detailed content of How to create perfect CSS circle sectors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn