技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運營

贊助商

分類目錄

贊助商

最新文章

搜索

詳細(xì)介紹CSS+SVG創(chuàng)建圓圈/圓環(huán)動畫

作者:admin    時間:2022-9-10 19:54:33    瀏覽:

本文是關(guān)于CSS+SVG創(chuàng)建圓圈/圓環(huán)動畫的教程,為那些對 SVG 感興趣的人提供了一個指南。

最終的效果

 

demodownload

創(chuàng)建 SVG 圓

第一個問題:如何建立一個圈子?讓我們從簡單的數(shù)學(xué)開始吧!圓的周長 = 2 * PI * 半徑。

公式:C = 2 × π × r

 

<svg> 
  <circle cx="100" cy="100" r="75" /> 
</svg>

如果你將代碼復(fù)制并粘貼到HTML文件中,用瀏覽器打開時將收到一個不完整的圓圈。為什么?當(dāng)你檢查<circle>元素時,你將知道答案。

y 軸坐標(biāo) (cy) 有問題嗎?

 

 作為解決方案,我們可以將cy值更改為75以使<circle>元素在y 軸上居中。同樣,對于cx值,將 300 除以 2。

代碼如下: 

<svg> 
  <circle cx="150" cy="75" r="75" /> 
</svg>

將 SVG 居中

接下來,這一步是可選的。如果你想將你的 SVG 放在網(wǎng)頁的中心,你可以按照下面的代碼:

svg {
  background: #ffece3;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

 中心<circle>元素
中心<circle>元素

為它創(chuàng)建動畫

我計劃以順時針方向為圓圈設(shè)置動畫。因此,我將 stroke-width 屬性添加到 10px。

circle {
    fill: transparent;
    stroke: orange;
    stroke-width: 10px;
}

 
10px寬的圓圈

哎呀!該<circle>元素沒有足夠的空間。讓我們把“空間”做大。因此,為 SVG 元素添加大約 400px 的寬度和高度。

然后,你需要通過將寬度和高度值除以2 或使用百分比(%)值來表??示 x 軸和 y 軸坐標(biāo)來再次調(diào)整它。 

<svg> 
  <circle cx="50%" cy="50%" r="75" /> 
</svg>

接下來,我們需要知道動畫stroke-dasharraystroke-dashoffset屬性。

CSS 中的stroke-dasharray屬性用于在 SVG 形狀的筆劃中創(chuàng)建破折號。

對于<circle>元素,該stroke-dasharray屬性表示圓的周長。

所以,我們可以得到該屬性的最大值。stroke-dasharray值越低,<circle>元素筆劃中短劃線之間的空間越大。

circle {
    fill: transparent;
    stroke: orange;
    stroke-width: 10px;
    stroke-dasharray: 471;
}

CSS 中的stroke-dashoffset屬性定義了 SVG 路徑上 stroke 的破折號開始的位置。

我試了stroke-dashoffset具有不同值的屬性。結(jié)果如下:

如果你用與stroke-dasharray相同的值,你會得到一個空的圓圈。所以,我們要為stroke-dashoffset屬性設(shè)置動畫?,F(xiàn)在,我們可以為<circle>元素聲明動畫了。

circle {
  fill: transparent;
  stroke: orange;
  stroke-width: 10px;
  stroke-dasharray: 471;
  stroke-dashoffset: 471;
  animation: clock-animation 10s linear infinite;
}
@keyframes clock-animation {
  0% {
    stroke-dashoffset: 471;
  }
  100% {
    stroke-dashoffset: 0;
  }
}

 
圓形動畫

問題:圓圈右側(cè)的起始動畫點?如何使起點從頂部開始?

解決方法:將圓圈旋轉(zhuǎn)到-90 度。并記住將transform-origin屬性添加到center。

circle {
  fill: transparent;
  stroke: orange;
  stroke-width: 10px;
  stroke-dasharray: 471;
  stroke-dashoffset: 471;
  animation: clock-animation 10s linear infinite;
  transform: rotate(-90deg);
  transform-origin: center;
}

 
-90 度圓變換

你也可以更改為逆時針方向。只需更改動畫代碼。

@keyframes anti-clock-animation {
  0% {
    stroke-dashoffset: 0;
  }
  100% {
    stroke-dashoffset: 471;
  }
}

附加的功能:

如果你想要一個完整的圓圈動畫,只需增加stroke-width值。假設(shè)圓的半徑為 75,然后將值加倍,即 150px。

 

總結(jié)

本文詳細(xì)介紹了CSS+SVG創(chuàng)建圓圈/圓環(huán)動畫的過程,希望你喜歡這個 SVG 教程。關(guān)于CSS+SVG創(chuàng)建圓環(huán)動畫的實例教程,除此之外,你也可以看看此文《[實例]純 CSS SVG 畫圓/圓環(huán)/圓弧動畫》,實例圖示如下:

相關(guān)文章

標(biāo)簽: css  SVG  圓圈  圓弧動畫  圓環(huán)動畫  動畫  
x
  • 站長推薦
/* 左側(cè)顯示文章內(nèi)容目錄 */