《Svg.js使用手册.doc》由会员分享,可在线阅读,更多相关《Svg.js使用手册.doc(38页珍藏版)》请在三一办公上搜索。
1、Svg.js使用手册简介:SVG.js是一个轻量级的JavaScript库,允许你轻松操作SVG和定义动画。SVG(Scalable Vector Graphics,可缩放矢量图形)是基于XML、用于描述二维矢量图形的一种图形格式。SVG由W3C制定,是一个开放标准。SVG.js中包含了大量用于定义动画的方法,如移动、缩放、旋转、倾斜等,具体可参阅相关演示。SVG.js中的一些亮点: 易读的简洁的语法 非常轻量,gzip压缩版只有5k 针对大小、位置、颜色等的动画元素 模块化结构,轻松扩展 各种实用插件 各种形状类型间拥有统一的API. 元素可以绑定事件,包括触摸事件 完全支持不透明蒙版 元素
2、组 动态渐变 填充模式 完整的文档记录使用说明:Create a SVG documentUse theSVG()function to create a SVG document within a given html element:var draw = SVG(canvas).size(300, 300)var rect = draw.rect(100, 100).attr( fill: #f06 )The first argument can either be an id of the element or the selected element itself. This will
3、 generate the following output: By default the svg canvas follows the dimensions of its parent, in this case#canvas:var draw = SVG(canvas).size(100%, 100%)Checking for SVG supportBy default this library assumes the clients browser supports SVG. You can test support as follows:if (SVG.supported) var
4、draw = SVG(canvas) var rect = draw.rect(100, 100) else alert(SVG not supported)ViewBoxTheviewBoxattribute of anelement can be managed with theviewbox()method. When supplied with four arguments it will act as a setter:draw.viewbox(0, 0, 297, 210)Alternatively you can also supply an object as the firs
5、t argument:draw.viewbox( x: 0, y: 0, width: 297, height: 210 )Without any arguments an instance ofSVG.ViewBoxwill be returned:var box = draw.viewbox()But the best thing about theviewbox()method is that you can get the zoom of the viewbox:var box = draw.viewbox()var zoom = box.zoomIf the size of the
6、viewbox equals the size of the svg canvas, the zoom value will be 1.Nested svgWith this feature you can nest svg documents within each other. Nested svg documents have exactly the same features as the main, top-level svg document:var nested = draw.nested()var rect = nested.rect(200, 200)This functio
7、nality requires the nested.js module which is included in the default distribution.SVG documentSvg.js also works outside of the HTML DOM, inside an SVG document for example: ElementsRectRects have two arguments, theirwidthandheight:var rect = draw.rect(100, 100)EllipseEllipses, like rects, have two
8、arguments, theirwidthandheight:var ellipse = draw.ellipse(200, 100)CircleThe only argument necessary for a circle is the diameter:var circle = draw.circle(100)Note that this generates anelement instead of a. This choice has been made to keep the size of the library down.LineThe line element always t
9、akes four arguments,x1,y1,x2andy2:var line = draw.line(0, 0, 100, 150).stroke( width: 1 )PolylineThe polyline element defines a set of connected straight line segments. Typically, polyline elements define open shapes:/ polyline(x,y x,y x,y)var polyline = draw.polyline(0,0 100,50 50,100).fill(none).s
10、troke( width: 1 )Polyline strings consist of a list of points separated by spaces:x,y x,y x,y.As an alternative an array of points will work as well:/ polyline(x,y, x,y, x,y)var polyline = draw.polyline(0,0, 100,50, 50,100).fill(none).stroke( width: 1 )Polylines can be updated using theplot()method:
11、polyline.plot(0,0, 100,50, 50,100, 150,50, 200,50)Theplot()method can also be animated:polyline.animate(3000).plot(0,0, 100,50, 50,100, 150,50, 200,50, 250,100, 300,50, 350,50)PolygonThe polygon element, unlike the polyline element, defines a closed shape consisting of a set of connected straight li
12、ne segments:/ polygon(x,y x,y x,y)var polygon = draw.polygon(0,0 100,50 50,100).fill(none).stroke( width: 1 )Polygon strings are exactly the same as polyline strings. There is no need to close the shape as the first and last point will be connected automatically.PathThe path string is similar to the
13、 polygon string but much more complex in order to support curves:/ path(path data)var path = draw.path(M10,20L30,40)For more details on path data strings, please refer to the SVG documentation:http:/www.w3.org/TR/SVG/paths.html#PathDataNote that paths will always be positioned at x=0, y=0 on creatio
14、n. This is to make the unifiedmove()api possible. Svg.js assumes you are creating a path to move it afterwards. If you need to constantly update your path you probably dont want to use themove()method at all. In that case you can create an unbiased path like so:/ path(path data, unbiased)var path =
15、draw.path(M10,20L30,40, true)This logic is also applicable to polylines and polygons.ImageWhen creating images thewidthandheightvalues should be defined:/ image(src, width, height)var image = draw.image(/path/to/image.jpg, 200, 200).move(100, 100)TextUnlike html, text in svg is much harder to tame.
16、There is no way to create flowing text, so newlines should be entered manually. In svg.js there are two ways to create text elements.The first and easiest method is to provide a string of text, split by newlines:var text = draw.text(Lorem ipsum dolor sit amet consectetur.nCras sodales imperdiet auct
17、or.)This will automatically create a block of text and insert newlines where necessary.The second method will give you much more control but requires a bit more code:var text = draw.text(function(add) add.tspan(Lorem ipsum dolor sit amet ).newLine() add.tspan(consectetur).fill(#f06) add.tspan(.) add
18、.tspan(Cras sodales imperdiet auctor.).newLine().dx(20) add.tspan(Nunc ultrices lectus at erat).newLine() add.tspan(dictum pharetra elementum ante).newLine()Changing text afterwards is also possible with thetext()method:text.text(Brilliant!)To get the raw text content:text.contentThe sugar.js module
19、 provides some syntax sugar specifically for this element type:text.font( family: Helvetica, size: 144, anchor: middle, leading: 1.5em)TextPathA nice feature in svg is the ability to run text along a path:var text = draw.text(function(add) add.tspan(We go ) add.tspan(up).fill(#f09).dy(-40) add.tspan
20、(, then we go down, then up again).dy(40)text .path(M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100) .font( size: 42.5, family: Verdana )When calling thepath()method on a text element, the text element is mutated into an intermediate between a text and a path el
21、ement. From that point on the text element will also feature aplot()method to update the path:text.plot(M 300 500 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100)Attributes specific to theelement can be applied to the textPath instance itself:text.textPath.attr(startOffse
22、t, 0.5)And they can be animated as well of course:text.textPath.animate(3000).attr(startOffset, 0.8)Referencing the linked path element directly:var path = text.trackUseThe use element simply emulates another existing element. Any changes on the master element will be reflected on all theuseinstance
23、s. The usage ofuse()is very straightforward:var rect = draw.rect(100, 100).fill(#f09)var use = draw.use(rect).move(200, 200)In the case of the example above two rects will appear on the svg canvas, the original and theuseinstance. In some cases you might want to hide the original element. the best w
24、ay to do this is to create the original element in the defs node:var rect = draw.defs().rect(100, 100).fill(#f09)var use = draw.use(rect).move(200, 200)In this way the rect element acts as a library element. You can edit it but it wont be rendered.Referencing elementsBy idIf you want to get an eleme
25、nt created by svg.js by its id, you can use theSVG.get()method:var element = SVG.get(my_element)element.fill(#f06)By class nameThere is no DOM querying system built into svg.js butjQueryorZeptowill hep you achieve this. Here is an example:/* add elements */var draw = SVG(canvas)var group = draw.grou
26、p().attr(class, my-group)var rect = group.rect(100,100).attr(class, my-element)var circle = group.circle(100).attr(class, my-element).move(100, 100)/* get elements in group */var elements = $(#canvas g.my-group .my-element).each(function() this.instance.animate().fill(#f09)Circluar referenceEvery el
27、ement instance within svg.js has a reference to the actualnode:element.nodeSimilarly, the node carries a reference to the svg.jsinstance:node.instanceManipulating elementsAttributesYou can get and set an elements attributes directly usingattr().Get a single attribute:rect.attr(x)Set a single attribu
28、te:rect.attr(x, 50)Set multiple attributes at once:rect.attr( fill: #f06, fill-opacity: 0.5, stroke: #000, stroke-width: 10)Set an attribute with a namespace:rect.attr(x, 50, http:/www.w3.org/2000/svg)Explicitly remove an attribute:rect.attr(fill, null)TransformWith thetransform()method elements can
29、 be scaled, rotated, translated and skewed:rect.transform( rotation: 45, cx: 100, cy: 100)You can also provide two arguments as property and value:rect.transform(matrix, 1,0.5,0.5,1,0,0)All available transformations are:rect.transform( x: translation on x-axis, y: translation on y-axis, rotation: de
30、grees, cx: x rotation point, cy: y rotation point, scaleX: scaling on x-axis, scaleY: scaling on y-axis, skewX: skewing on x-axis, skewY: skewing on y-axis, matrix: a 6-digit matrix string; e.g. 1,0,0,1,0,0, a: the first matrix digit, b: the second matrix digit, c: the third matrix digit, d: the fou
31、rth matrix digit, e: the fifth matrix digit, f: the sixth matrix digit)Note that you can also apply transformations directly using theattr()method:rect.attr(transform, matrix(1,0.5,0.5,1,0,0)Although that would mean you cant use thetransform()method because it would overwrite any manually applied tr
32、ansformations. You should only go down this route if you know exactly what you are doing and you want to achieve an effect that is not achievable with thetransform()method.StyleWith thestyle()method thestyleattribute can be managed like attributes withattr:rect.style(cursor, pointer)Multiple styles
33、can be set at once using an object:rect.style( cursor: pointer, fill: #f03 )Or a css string:rect.style(cursor:pointer;fill:#f03;)Similarly toattr()thestyle()method can also act as a getter:rect.style(cursor)/ = pointerOr even a full getter:rect.style()/ = cursor:pointer;fill:#f03;Explicitly deleting
34、 individual style definitions works the same as with theattr()method:rect.style(cursor, null)MoveMove the element to a givenxandyposition by its upper left corner:rect.move(200, 350)This will have the same effect as:rect.x(200).y(350)Note that you can also use the following code to move elements aro
35、und:rect.attr( x: 20, y: 60 )Althoughmove()is much more convenient because it will always use the upper left corner as the position reference, whereas with usingattr()thexandyreference differ between element types. For example, rect uses the upper left corner with thexandyattributes, circle and elli
36、pse use their center with thecxandcyattributes and thereby simply ignoring thexandyvalues you might assign.Thetextelement has one optional argument:/ move(x, y, anchor)rect.move(200, 350, true)The third argument can be used to move the text element by its anchor point rather than the calculated left
37、 top position. This can also be used on the individual axes:rect.x(200, true).y(350, true)CenterThis is an extra method to move an element by its center:rect.center(150, 150)This will have the same effect as:rect.cx(150).cy(150)Thetextelement has one optional argument:/ center(x, y, anchor)rect.cent
38、er(150, 150, true)The third argument can be used to center the text element by its anchor point rather than the calculated center position. This can also be used on the individual axes:rect.cx(150, true).cy(150, true)SizeSet the size of an element by a givenwidthandheight:rect.size(200, 300)Same as
39、withmove()the size of an element could be set by usingattr(). But because every type of element is handles its size differently thesize()method is much more convenient.Hide and showWe all love to have a little hide:rect.hide()and show:rect.show()To check if the element is visible:rect.visible()Remov
40、ing elementsPretty straightforward:rect.remove()To remove all elements in the svg document:draw.clear()Bounding boxpath.bbox()This will return an instance ofSVG.BBoxcontaining the following values: height: 20, width: 20, y: 20, x: 10, cx: 30, cy: 20 As opposed to the nativegetBBox()method any transl
41、ations used with thetransform()method will be taken into account.TheSVG.BBoxhas one other nifty little feature, enter themerge()method. Withmerge()twoSVG.BBoxinstances can be merged into one new instance, basically being the bounding box of the two original bounding boxes:var box1 = draw.rect(100,10
42、0).move(50,50)var box2 = draw.rect(100,100).move(200,200)var box3 = box1.merge(box2)Rectagular boxIs similar tobbox()but will give you the box around the exact representation of the element, taking all transformations into account.path.rbox()This will return an instance ofSVG.RBox.Iterating over all
43、 childrenIf you would iterate over all thechildrenof the svg document, you might notice also theandelements will be included. To iterate the shapes only, you can use theeach()method:draw.each(function(i, children) this.fill( color: #f06 )Deep traversing is also possible by passing true as the second argument:/ draw.each(block, deep)draw.each(function(i, children) this.fill( color: #f06 ), true)ColorsSvg.js has a dedicated color module handling different types of colors. Accepted values are: hex string; three based (e.g.