SVG图——基于数学的描述
使用方式:
- 浏览器直接打开
- 在HTML中使用
<img>
标签引用 - 直接在HTML中使用
<svg>
标签 - 作为CSS背景
如:
<img src="如 simplr.svg" width="50" height="50" />
和一般img不同,这个地方的width和height可以改!
SVG绘图书写格式(大概)
其不同图形有不同格式,但都包裹在一个标签中 —— <svg>
<svg xmlns="http://www.w3.org/2000/svg">
...
</svg>
…
/* 对于长方形: */
<rect
x="10"
y="10"
width="150"
height="100"
stroke="red"
fill="none">
</rect>
/* 对于圆: */
<circle
cx="250"
cy="60"
r="50"
stroke="red"
fill="none">
</circle>
/* 对于直线: */
<line
x1="10"
y1="120"
x2="160"
y2="220"
stroke="red">
</line>
/* 对于折线 */
<polyline
points="250 120
300 220
200 220"
stroke="red"
fill="none">
</polyline>
SVG中的图形分组
<g>
标签创建分组 transform属性定义座标改变 属性继承
比如:“一个锤子” —— 一般我们移动通过改变每个x/y,改变颜色我们通过修改每个stroke;
现在通过 分组 ,把共有属性 如stroke、fill 放在g标签内,整体移动的话就在<g>
内添加transform属性。
下面代码:
<svg xmlns="http://www.w3.org/2000/svg">
<g stroke="green" fill="none" transform="translate(0,50)">
<rect x="100" y="50" width="100" height="50"></rect>
<rect x="140" y="100" width="20" height="120"></rect>
</g>
</svg>
SVG的使用——“打标记”
在需要是使用svg图的地方引入<svg>
标签,格式如下:
<svg data-src="svg文件路径" width="..." height="..."></svg>
然后配合下面的JS代码使用。
使用bower管理(前端)包依赖
- npm install bower -g
- 添加jQuery依赖:bower install jquery --save
- 安装已定义bower包(bower.json)的项目的依赖:bower install
(JS)动态加载SVG
前面所说我们用data-src属性,那么我们将它取出来:
$(function(){
$('svg['data-src']').each(function(index,svg){
var src=$(svg).data('src');
$.ajax({
url:src,
dataType:'xml',
success:function(svgDocument){
var $doc=$(svgDocument.documentElement);
$doc.attr({
width:$(svg).attr('width');
height:$(svg).attr('height');
});
$(svg).after($doc).remove();
}
});
});
});
总结来说,其
优势: 保持svg文件的独立,方便编辑、维护;
思路:
- 在原本Dom中记录文件路径
- 脚本“扫描”记录的记录,用Ajax请求加载
- 替换掉原本用做记录的Dom