前端實現實心半圓和空心半圓的幾種方式

在前端開發中,有時候我們會遇到使用半圓的情境,比如在優惠券中,如下圖所示:

優惠券示例

本文將介紹如何使用不同的技術實現實心半圓和空心半圓。我們將覆蓋三種主要的實現方式:CSS、SVG和Canvas。每種方法都包含詳細的代碼示例和解釋。

實現實心半圓

使用 CSS

透過適當的 border-radius 設置,可以創建實心半圓。如下所示:

1
<div class="square-solid-half-circle"></div>
2
3
<style>
4
.square-solid-half-circle {
5
width: 100px;
6
height: 50px; /* 高度為半個圓的高度 */
7
background-color: #3498db;
8
border-top-left-radius: 50px;
9
border-top-right-radius: 50px;
10
}
11
</style>

css實現的實心半圓

解釋:

  • widthheight 設置了寬高。
  • background-color 設置了半圓的填充顏色。
  • border-top-left-radiusborder-top-right-radius 設置了圓角,使其成為半圓形狀。

使用 SVG

SVG 提供了精確繪製半圓的功能。以下是實現實心半圓的代碼示例:

1
<svg width="100" height="50">
2
<path d="M 0 50 A 50 50 0 0 1 100 50" fill="#3498db" />
3
</svg>

解釋:

  • path 元素中的 A 指令繪製了半圓弧,fill 設置了填充顏色。

使用 Canvas

Canvas API 允許我們使用 JavaScript 動態繪製圖形。以下是實心半圓的實現:

1
<canvas id="solid-half-circle" width="100" height="50"></canvas>
2
3
<script>
4
const solidCanvas = document.getElementById("solid-half-circle");
5
const solidCtx = solidCanvas.getContext("2d");
6
7
solidCtx.beginPath();
8
solidCtx.arc(50, 50, 50, Math.PI, 0, false); // 圓心 (50,50), 半徑 50, 從 π 到 0 弧度
9
solidCtx.fillStyle = "#3498db"; // 設置填充顏色
10
solidCtx.fill(); // 填充路徑
11
</script>

canvas實現的實心半圓

解釋:

  • arc 方法繪製了半圓的弧線,fillStyle 設置填充顏色,fill 方法將其填充為實心半圓。

實現空心半圓

使用 CSS

我們可以透過一個正方形設置邊框顏色,同時把下邊框和右邊框設置為透明,然後透過旋轉實現。以下是實現代碼:

1
<div class="square-hollow-half-circle"></div>
2
3
<style>
4
.square-hollow-half-circle {
5
width: 100px;
6
height: 100px;
7
border: 5px solid #3498db; /* 設置邊框顏色和寬度 */
8
border-radius: 100%; /* 使邊框成圓形 */
9
border-bottom-color: transparent; /* 隱藏底部邊框 */
10
border-right-color: transparent;
11
box-sizing: border-box; /* 包括邊框在內計算寬度和高度 */
12
transform: rotate(45deg); /* 旋轉 45 度 */
13
}
14
</style>

css實現的空心半圓

解釋:

  • border 設置了邊框,border-radius 使其成為圓形。
  • border-bottom-colorborder-right-color 設置為透明以隱藏邊框。
  • transform: rotate(45deg) 用於旋轉。

使用 SVG

SVG 中,利用兩個路徑,一個大半圓和一個小半圓的遮罩來實現空心半圓:

1
<svg width="100" height="50">
2
<!-- 實心半圓 -->
3
<path d="M 0 50 A 50 50 0 0 1 100 50 L 0 50 Z" fill="#3498db" />
4
<!-- 覆蓋的白色半圓 -->
5
<path d="M 5 50 A 45 45 0 0 1 95 50 L 5 50 Z" fill="#ffffff" />
6
</svg>

解釋:

  • 第一個 path 元素繪製了實心半圓。
  • 第二個 path 元素繪製了一個小的白色半圓,遮罩在大半圓之上。

使用 Canvas

同理,在Canvas 中,我們可以使用兩個 arc 繪製外圓和內圓,實現空心半圓:

1
<canvas id="canvas-hollow-half-circle-overlay" width="100" height="50"></canvas>
2
3
<script>
4
const canvasOverlay = document.getElementById(
5
"canvas-hollow-half-circle-overlay",
6
);
7
const ctxOverlay = canvasOverlay.getContext("2d");
8
9
// 實心半圓
10
ctxOverlay.beginPath();
11
ctxOverlay.arc(50, 50, 50, Math.PI, 0, false);
12
ctxOverlay.fillStyle = "#3498db";
13
ctxOverlay.fill();
14
15
// 覆蓋的白色半圓
16
ctxOverlay.beginPath();
17
ctxOverlay.arc(50, 50, 45, Math.PI, 0, false);
18
ctxOverlay.fillStyle = "#ffffff";
19
ctxOverlay.fill();
20
</script>

canvas實現的空心半圓

解釋:

  • 繪製外圈的實心半圓,然後在其上繪製一個小的白色半圓,以形成空心效果。

透過以上方法,我們可以在前端實現實心和空心半圓的各種效果。