javascript - 公式为svg中的动态间距
问题描述
如何根据编号制作动态间距。返回的数据?我希望如果只返回一个数据,它位于中间。如果返回两个数据,它将调整,依此类推。
var prev = {
"Prev": [{
"type": "Prev1",
},
{
"type": "Prev2",
},
{
"type": "Prev3",
},
]
};
var draw = document.getElementById('drawing');
prev.Prev.forEach((p, i, arr) => {
let x = 55;
let y = 250/arr.length*i+50;
draw.innerHTML += `<g transform="translate(${x} ${y})">
<rect x="-50" y="-20" width="100" height="40" rx="10" />
<text dominant-baseline="middle" text-anchor="middle" width="100">${p.type}</text>
<line x1="50" y1="0" x2="100" y2="${250/arr.length-y+50}" />
</g>`;
});
draw.innerHTML += `<g>
<rect x="150" y="110" width="100" height="40" rx="10" />
<text x="200" y="130" dominant-baseline="middle" text-anchor="middle" width="100">BASE</text>
</g>`;
line, rect {stroke-width: 1; stroke: navy; fill: none;}
text {fill: navy;}
<svg id="drawing" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg">
</svg>
解决方案
这很简单。您只需要计算第一个矩形的顶部,然后将i
一个项目顶部到下一个项目顶部的距离相加。
var prev = {
"Prev": [{
"type": "Prev1",
},
{
"type": "Prev2",
},
{
"type": "Prev3",
}
]
};
var draw = document.getElementById('drawing');
var RECT_HEIGHT = 40;
var RECT_SPACING = 50;
var SVG_HEIGHT = 300;
prev.Prev.forEach((p, i, arr) => {
// number of rects/graph items
let num = arr.length;
// total height of all <num>
let totalHeight = num * RECT_HEIGHT + (num - 1) * RECT_SPACING;
let x = 55;
// final position = position of first rect + i * distance_between_rects
let y = (SVG_HEIGHT - totalHeight) / 2 // top of first rect
+ i * (RECT_HEIGHT + RECT_SPACING); // i * distance_between_rects
draw.innerHTML += `<g transform="translate(${x} ${y})">
<rect x="-50" y="0" width="100" height="40" rx="10" />
<text y="20" dominant-baseline="middle" text-anchor="middle"
width="100">${p.type}</text>
<line x1="50" y1="20" x2="100" y2="${SVG_HEIGHT / 2 - y}" />
</g>`;
});
/*
draw.innerHTML += `<g>
<rect x="150" y="110" width="100" height="40" rx="10" />
<text x="200" y="130" dominant-baseline="middle" text-anchor="middle" width="100">BASE</text>
</g>`;
*/
svg {
background: linen;
}
<svg id="drawing" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg">
<style>
line, rect {stroke-width: 1; stroke: navy; fill: none;}
text {fill: navy;}
</style>
</svg>
推荐阅读
- javascript - 在 Codeceptjs 中没有有效负载的 SendPostRequest
- java - Apache Lucene 索引器搜索
- ruby-on-rails - 使用 Ruby on Rails 仔细检查/帮助建模关系
- python - 无法使用pymysql连接到mysql
- ruby-on-rails - 如何阻止我网站上的用户访问 Rails_admin 面板 URL?
- python - 将矩阵发送到 Tensorflow-Serving 模块
- c# - Request.Form 与会话 MVC C#
- arrays - 在 ruby 中转换数组的哈希
- c# - 如何强制 WCF 对小于 768 字节的文件使用 MTOM 编码?
- git - 通过 REST API Bitbucket 将主分支(HotFixes)合并到功能分支中