Snap的使用
創建SVG
var svg = Snap(100, 100); svg.paper.circle(50,50,40); document.getElementById("append").appendChild(svg.node);
獲取頁面上的svg
var svg = Snap("#svg");
Paper的使用
通過svg.paper對象可以在svg里進行圖形化繪制
畫線
svg.paper.line(x1, y1, x2, y2)
畫矩形
svg.paper.rect(x,y,width,height,rx,ry)
畫折線
svg.paper.polyline(x1,y1,x2,y2)
或
svg.paper.polyline([x1,y1,x2,y2])
畫多邊形
svg.paper.polygon(x1,y1,x2,y2);
或
svg.paper.polygon([x1,y1,x2,y2]
畫圓
svg.paper.circle(cx,cy,r);
畫橢圓
svg.paper.ellipse(cx,cy,rx,ry)
畫路徑
svg.paper.path(pathString)
寫文字
svg.paper.text(x,y,text)
分組
var svg = Snap("#svg"); var c1 = svg.paper.circle(50, 50, 40); c2 = svg.paper.rect(150, 10, 120, 80); var g = svg.paper.g(); g.add(c2, c1);
濾鏡
var svg = Snap("#svg"); var f = svg.paper.filter('<feGaussianBlur stdDeviation="2"/>'); var c = svg.circle(50, 50, 40).attr({ filter: f });
畫任意元素
var svg = Snap("#svg"); svg.paper.el("circle", { cx: 50, cy: 50, r: 40 }); // 等同於svg.circle(50, 50, 40);
Element的使用
通過svg對象查詢對象
查詢一個對象 select
//例子:將第一個圓填充紅色 var svg = Snap("#svg"); svg.select("circle").attr({ fill: "#f00" });
查詢多個對象 selectAll
//例子:將所有的圓填充紅色 var svg = Snap("#svg"); svg.selectAll("circle").attr({ fill: "#f00" });
值得一提的是,執行selectAll方法將返回一個Set對象,該對象有一些具體的用法在開發中也經常使用,如遍歷,更多使用方法請點擊菜單"Set的使用"
獲取或設置元素屬性 attr
element.attr("width"); //獲取屬性 element.attr("width":"50"); //設置屬性
在元素上綁定值
circle.data("state",1); //為circle元素綁定一個state值 circel.data("state"); //獲取circle元素上綁定的state值 circle.removeData("state"); //移除circle元素上綁定的值,如果不傳遞參數,將移除該元素所有綁定的值
元素插入與刪除
insertAfter
c1.insertAfter(c2); //將c1插入到c2后面
insertBefore
c1.insertBefore(c2); //將c1插入到c2前面
append
c1.append(c2); //在c1的最后面插入c2
after
c1.after(c2); //將c1調換到c2后面
remove
c1.remove(); //移除元素
元素事件處理
鼠標單擊事件
c1.click(function(){ //事件處理代碼 }); c1.unclick(); //刪除鼠標點擊事件
鼠標雙擊事件
c1.dblclick(function(){ //事件處理代碼 }); c1.undblclick(); //刪除鼠標雙擊事件
鼠標移入事件
c1.mouseover(function(){ //事件處理代碼 }); c1.unmouseover(); //刪除鼠標移入事件
鼠標移出事件
c1.mouseout(function(){ //事件處理代碼 }); c1.unmouseout(); //刪除鼠標移出事件
鼠標拖拽事件
c1.drag();
c1.undrag();
設置和獲取矩陣變換
c1.transform(); //獲取 c1.transform(matrix); //設置元素的矩陣變換
矩陣變換在svg的縮放,平移中將會被頻繁用到,值得一看。
其它元素操作
獲取父節點
c1.parent(); //獲取元素c1的父節點
設置動畫
Element.animate(attrs, duration, [easing], [callback])
更多api參考:
中文:http://www.zhangxinxu.com/GitHub/demo-Snap.svg/demo/basic/