Skip to content

Instantly share code, notes, and snippets.

@shawndxl
Last active December 22, 2020 23:54
Show Gist options
  • Save shawndxl/c29279c7785da2d988de6f558e9ab7d5 to your computer and use it in GitHub Desktop.
Save shawndxl/c29279c7785da2d988de6f558e9ab7d5 to your computer and use it in GitHub Desktop.
用 CSS 来设置 SVG ( Style SVG using CSS ) & SVG 用法汇总

The SVG !

先上链接

SVG 的几种用法

An SVG can be embedded in any of the following ways:

1. as an image using the < img > tag:

<img src="mySVG.svg" alt="" />

2. as a background image in CSS:

.el { background-image: url(mySVG.svg); }

3. as an object using the < object > tag:

<object type="image/svg+xml" data="mySVG.svg"><!-- fallback here --></object>

4. as an iframe using an < iframe > tag:

<iframe src="mySVG.svg"><!-- fallback here --></iframe>

5. using the < embed > tag:

<embed type="image/svg+xml" src="mySVG.svg" />

6. inline using the < svg > tag:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<!-- svg content -->
</svg>

Code Pen Demo Test

See the Pen svg test by shawn (@dongxl) on CodePen.

<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

学习 svg inline 的基本用法 以及 SMIL 的基本用法,这样才能更好的理解 css 、 greensock 的替代方法

重点理解 svg 的 path 的用法,例如

<svg>
<path d='M 100 100, L 100 150' />
<!-- M 简单理解为起点的意思,L 表示化直线,上面也就是先定义了一个起点,然后化直线到第二个坐标,也就是这条线的终点 -->
<!-- 直接运行上边的例子可能发现没有内容,其实是有的,只是我们需要定义这条 path 的颜色以及宽度才可以看的见,设置下边两个属性 -->
<path d='M 100 100, L 100 150' stroke='red' stroke-width='2' />
<!-- svg 定义路径靠的是一条一条包含坐标的不同命令,比如上方的m、l,常用的还有 c 曲线,这些字母的大小写有不同含义,大写表示绝对定位,小写表示相对定位,详情查看上方链接张鑫旭写的三次贝塞尔曲线在css、svg、canvas中的应用 -->
<path d='M 153 334, C 133 374, 173 394, 153 434' stroke='red' stroke-width='2' />
<!-- 上方路径中的 坐标前后的逗号并不是必须的,只不过加上会有助于理解以及排版,所以我们甚至可以这些来帮助理解 -->
<path 
	d="
		M 153 334,
		C 133 374, 173 394, 153 434	
	"
	style="fill: none; stroke: red; stroke-width: 5;"
/>
</svg>
/* svg 的属性可以通过 css 设置,以便有足够的大小能够包裹其中的元素 */
svg {
  width: 100%;
  height: 100%;
  border: 1px solid red;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment