最近项目需要图形化方案的一个功能,选了好久结合实际需求还是选择了 raphaeljs ,因为兼容性还是比较正要的。像大名的D3,虽然如火如荼,但是不兼容IE8以下确实还是硬伤。好了,进入正题。

raphaeljs 是矢量图形库。提供了很多画图的方法,但是在实际工作中,不会是简单基于图形的图标,对于复杂矢量图形如何处理确实是第一道难题,所以我这次用illustrator做一个矢量图形,结合raphaeljs 做个一个小demo。效果还是不错的说。

开始 ——  先开下illustrator的矢量图形

20140617140451

用illustrator的另存为导出SVG图像,注意选项选择SVG的web标准。导出后编辑器打开查看代码,如下:

<?xml version=”1.0″ encoding=”utf-8″?>
<!– Generator: Adobe Illustrator 15.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  –>
<!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.1//EN” “http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd”>
<svg version=”1.1″ id=”图层_1″ xmlns=”http://www.w3.org/2000/svg” xmlns:xlink=”http://www.w3.org/1999/xlink” x=”0px” y=”0px”
width=”800px” height=”600px” viewBox=”0 0 800 600″ enable-background=”new 0 0 800 600″ xml:space=”preserve”>
<g>
<path fill-rule=”evenodd” clip-rule=”evenodd” fill=”none” stroke=”#007BC2″ stroke-miterlimit=”22.9256″ d=”M188.402,90.084
v130.889h-23.126v-90.884C169.514,112.471,176.76,98.56,188.402,90.084z”/>
<path fill-rule=”evenodd” clip-rule=”evenodd” fill=”none” stroke=”#007BC2″ stroke-miterlimit=”22.9256″ d=”M203.539,79.444
c37-16.302,90.663-0.044,99.561,53.235c2.64,75.867-66.068,85.209-88.622,76.462l-0.268,12.776h-10.672v-51.313
c24.321,25.918,72.534,10.943,71.169-29.308c-3.683-43.578-48.468-50.343-70.845-26.46L203.539,79.444z”/>
<path fill-rule=”evenodd” clip-rule=”evenodd” fill=”none” stroke=”#007BC2″ stroke-miterlimit=”22.9256″ d=”M253.317,144.448
h12.067c-1.906,43.821-63.803,42.633-65.961-0.284c3.056-38.42,52.608-46.786,65.545-7.905l-12.799-0.347
c-9.521-20.707-38.395-14.43-40.323,7.789C214.324,170.766,251.279,171.84,253.317,144.448z”/>
</g>
</svg>

可以看到代码分为三部分,和图形正好对应。<path>标签中包含一些属性,如fill、stroke等等,这些和raphaeljs的api也能对应。最后<path>中的属性d=”……”这些数据是我们需要在raphaeljs中用到的。

再来看raphaeljs的代码:

var planeLoad = [];
function paintMap(PL) {
var attr = {
“fill”: “#97d6f5”,
“stroke”: “#007BC2”,
“stroke-width”: 1
};

planeLoad.test1 = {
name: ‘ONE’,
path: PL.path(“M188.402,90.084v130.889h-23.126v-90.884C169.514,112.471,176.76,98.56,188.402,90.084z”).attr(attr)
}
planeLoad.test2 = {
name: ‘TWO’,
path: PL.path(“M203.539,79.444c37-16.302,90.663-0.044,99.561,53.235c2.64,75.867-66.068,85.209-88.622,76.462l-0.268,12.776h-10.672v-51.313c24.321,25.918,72.534,10.943,71.169-29.308c-3.683-43.578-48.468-50.343-70.845-26.46L203.539,79.444z”).attr(attr)
}
planeLoad.test3 = {
name: ‘THREE’,
path: PL.path(“M253.317,144.448h12.067c-1.906,43.821-63.803,42.633-65.961-0.284c3.056-38.42,52.608-46.786,65.545-7.905l-12.799-0.347c-9.521-20.707-38.395-14.43-40.323,7.789C214.324,170.766,251.279,171.84,253.317,144.448z”).attr(attr)
}
}

其中path: PL.path(“……”)用到的就是illustrator导出后的内容。在html部分生成图形,并增加鼠标事件,具体方法和事件查看raphaeljs官方api即可,最后运行效果如图。

232323422

附上DEMO文件下载