1.5.4 • Published 3 years ago
js2svg v1.5.4
js2svg
这是一个将js数据转换svg元素字符串的方法
使用js2svg
安装
npm install js2svg
引入
import Js2svg from 'js2svg'
调用方法
// 传入一个data数据,data数据应该包含这个几个字段
import Js2svg from 'js2svg'
const data = {
tagName: '标签名称',
attributes: {
// 属性参数
},
style: {
// 样式参数
},
children: [
// 子元素,子元素的数据结构也是data类型的数据
],
strict: true // 是否严格模式,严格模式下,不会解析attributes和style属性内的没有定义的数据
}
const js2svg = new Js2svg(data)
示例
import Js2svg from 'js2svg'
const data = {
tagName: 'svg',
attributes: {
id: 'canvas',
width: 400,
height: 400,
version: '1.1',
xmlns: 'http://www.w3.org/2000/svg',
'xmlns:xlink': 'http://www.w3.org/1999/xlink'
},
children: [{
tagName: 'rect',
strict: true,
attributes: {
width: 100,
height: 100,
transform: {
translate: [10, 10]
}
},
style: {
fill: 'none',
stroke: '#147aff',
strokeWidth: 1
}
}, {
tagName: 'rect',
strict: true,
attributes: {
width: 100,
height: 100,
transform: {
translate: [120, 10]
}
},
style: {
fill: 'none',
stroke: '#147aff',
strokeWidth: 1
}
}, {
tagName: 'polygon',
attributes: {
points: [[10, 20], [100, 80], [30, 100]]
},
style: {
fill: '#147aff'
}
}, {
tagName: 'line',
attributes: {
x1: 300,
x2: 100,
y1: 100,
y2: 200
},
style: {
stroke: 'green',
strokeWidth: 10,
strokeDasharray: [20, 100]
}
}, {
tagName: 'path',
attributes: {
direct: [['M', [100, 100]],
['Q', [[120, 80], [140, 100]]],
['Q', [[160, 140], [180, 120]]],
{
order: 'Q',
value: [[200, 100], [220, 120]]
}]
},
style: {
fill: 'none',
stroke: 'green',
strokeWidth: 2,
}
}]
}
const js2svg = new Js2svg(data)
console.log(js2svg)
最终打印结果
<svg id="canvas" width="400" height="400" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><rect width="100" height="100" transform="translate(10, 10) rotate(0)" style="fill:none;stroke:#147aff;stroke-width:1;"></rect><rect width="100" height="100" transform="translate(120, 10) rotate(0)" style="fill:none;stroke:#147aff;stroke-width:1;"></rect><polygon points="10,20 100,80 30,100" style="fill:#147aff;"></polygon><line x1="300" x2="100" y1="100" y2="200" style="stroke:green;stroke-width:10;stroke-dasharray:20 100;"></line><path d="M100,100 Q120,80 140,100 Q160,140 180,120 Q200,100 220,120" style="fill:none;stroke:green;stroke-width:2;"></path></svg>
文档持续更新中