一、SVGPath簡介
SVG(Scalable Vector Graphics)是一種基於XML的矢量圖形格式,是W3C制定的標準。SVGPath是一個強大的路徑解析庫,它可以將SVG路徑指令解析成可用的數據結構,也可以將數據結構轉換成SVG路徑字符串。 該庫支持所有SVG路徑指令及其變體,例如:M,L,H,V,C,S,Q,T,A以及Z指令。同時還支持相對命令和絕對命令,也支持簡寫形式和完整形式。
二、SVGPath使用
1、安裝SVGPath庫
可以使用npm進行安裝,命令如下:
npm install svgpath
2、使用SVGPath庫
在你的應用程序中導入SVGPath:
const { SVGPathData, SVGPathTransformer, makeAbsolute } = require('svgpath');
3、解析SVG路徑指令
使用SVGPathTransformer.transform方法可以將SVG路徑指令解析成可用的SVGPathData對象,SVGPathData對象是SVGPathTransformer解析的結果,可以用於生成SVG路徑字符串:
const transformer = new SVGPathTransformer('M 100 100 L 300 100 L 200 300 z'); const pathData = transformer.transform(); console.log(pathData);
輸出結果為:
SVGPathData { getCommands: [Function: getCommands], commands: [ MoveToAbsCommand {command: "M", x: 100, y: 100}, LineToAbsCommand {command: "L", x: 300, y: 100}, LineToAbsCommand {command: "L", x: 200, y: 300}, ClosePathCommand {command: "z"} ], fromArray: [Function: fromArray], toArray: [Function: toArray], toAbs: [Function: toAbs], toRel: [Function: toRel], toString: [Function: toString], toSVGString: [Function: toSVGString], iter: [Function: iter], bbox: [Function: bbox] }
SVGPathData.commands是一個SVGPathCommand數組,可以通過getCommands方法獲取。SVGPathCommand對象表示SVG路徑指令。每個SVGPathCommand對象都有command屬性和一些特定的屬性,例如MoveToAbsCommand對象有x和y屬性。可以使用toArray和toString方法將SVGPathCommand數組轉換為SVG路徑字符串。
4、SVGPath操作
1、SVGPathData對象的轉換
使用makeAbsolute方法可以將SVGPathData對象中的相對命令轉換為絕對命令:
const absolutePathData = makeAbsolute(pathData); console.log(absolutePathData.toString());
輸出結果為:
M 100 100 L 300 100 L 200 300 Z
2、SVGPathCommand對象的操作
可以使用SVGPathCommand對象的toAbs方法和toRel方法將命令轉換為絕對命令和相對命令:
const mover = new MoveToAbsCommand(100, 100); const moverAbs = mover.toAbs(); console.log(moverAbs.toString()); // M 100 100 const moverRel = moverAbs.toRel(); console.log(moverRel.toString()); // m 100 100
3、SVGPathCommand數組的操作
可以使用SVGPathData.toArray方法和fromArray方法將SVGPathCommand數組轉換為普通數組和SVGPathData對象:
const commands = pathData.toArray(); console.log(commands); // ['M', 100, 100, 'L', 300, 100, 'L', 200, 300, 'Z'] const newData = SVGPathData.fromArray(commands); console.log(newData.toSVGString()); // M 100 100 L 300 100 L 200 300 Z
三、SVGPath擴展應用
1、SVGPathEditor
可以將SVGPath與SVGPathEditor結合使用,實現在線編輯SVG路徑指令的功能。SVGPathEditor是一個基於SVG和SVGPath的編輯器庫,通過SVGPathEditor可以在網頁中直接編輯SVG路徑,並實時生成SVG路徑指令。
示例代碼:
SVGPathEditor示例 #editor {
width: 800px;
height: 500px;
}原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/187844.html