iT邦幫忙

DAY 5
3

SVG 與 D3.js系列 第 5

SVG Defs 以及 CSS

  • 分享至 

  • xImage
  •  

歡迎來我Blog看完整範例:http://wcc723.github.io/d3js/2014/10/04/Ironman-30-days-05/

SVG內還有一個相當有趣的標簽<def>,用途是先定義一些圖形、漸層、形狀等等,甚至可以把它們群組起來,等待使用,如果用Illustrator 來介紹的話,就像是圖樣工具。

教程參考:http://tutorials.jenkov.com/svg/

漸層

我們先用<def>定義一個漸層的範圍,這難度比path簡單太多了...,在經過苦痛般的path鍛鍊,下面這段範例看完相信大家已經懂一半了。

簡易步驟:

  • 定義linearGradient,包含id、x,y位置、spreadMethod(展開的模式,這邊只會做簡單的範例)。
  • 設定每一段的色彩位置、顏色、透明度。
  • 套用

範例如下正方形,先定義好linearGradient標簽,並給予需要的屬性,最後在rect矩形內加入fill="url(#gradient)"就可以套用了。

<svg width="100%" height="180">
<defs>
<linearGradient id="gradient"
x1="0%" y1="0%"
x2="0%" y2="100%"
spreadMethod="pad">
<stop offset="0%" stop-color="DodgerBlue" stop-opacity="1"/>
<stop offset="50%" stop-color="DeepSkyBlue" stop-opacity="1"/>
<stop offset="100%" stop-color="white" stop-opacity="0"/>
</linearGradient>
</defs>
<rect x="5" y="5" width="150" height="150" fill="url(#gradient)" />
</svg>

結合CSS

先前都沒有介紹到SVG與CSS的關係,其實大部份的SVG屬性都可以用CSS去控制,所以這部分在用CSS去強化漸層的運用。

This demo only for webkit

以下有完整的程式碼,但特別注意,CSS的transform使用在SVG上,transform-origin的位置會受x、y改變,所以在用一個<g>群組包起來。另外我這有寫Hover的效果,也可以試試看(只是改Stroke的寬度而已)。

<svg width="100%" height="180">
<defs>
<linearGradient id="gradient"
x1="0%" y1="0%"
x2="0%" y2="100%"
spreadMethod="pad">
<stop offset="0%" stop-color="DodgerBlue" stop-opacity="1"/>
<stop offset="50%" stop-color="DeepSkyBlue" stop-opacity="1"/>
<stop offset="100%" stop-color="white" stop-opacity="0"/>
</linearGradient>
</defs>
<g class="pos">
<circle class="circle1" cx="0" cy="0" r="79" />
</g>
</svg>

//css

@-webkit-keyframes rotate {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
}
}
.pos{
-webkit-transform: translate(82px, 82px);
}
.circle1{
background-position: center center;
background-repeat: no-repeat;
fill: none;
stroke-width: 3;
-webkit-transition: all .5s;
stroke: url(#gradient);
-webkit-animation: rotate 1s infinite linear;
}


上一篇
SVG 超硬派了解 path Arcs
下一篇
SVG Stroke , Marker 以及 CSS
系列文
SVG 與 D3.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言