使用 Snap SVG 和 JSON 对象数组绘制线条

Draw lines using Snap SVG and a JSON object array

我在数组中有以下 JSON 个对象,即

[{ "rec": "1", "region": "LEFT", "intrface": "Line-1" },{ "rec": "1", "region": "LEFT", "intrface": "Line-2" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-3" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-4" }]

根据区域值,我需要遍历数组中的每个 JSON 对象并使用 Snap SVG 绘制图像左侧的线条以及图像右侧的线条在上面 JSON.

中同时使用 "region" 值和 "intrface" 值

绘制这些 SVG 线时,我还需要在每条 SVG 线上方放置 "intrface" 的值,如 label/text,因为我迭代每个 JSON 对象。

这是我所追求的外观:假设我正在绘制进入服务器的输入(第 1 行和第 2 行)(我的图像在中间)和输出在右侧服务器(第 3 行和第 4 行)。

我的部分代码如下:

var my_data = '{ "rec": "1", "region": "LEFT", "intrface": "Line-1" },{ "rec": "1", "region": "LEFT", "intrface": "Line-2" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-3" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-4" }';

var jsonObj = JSON.parse('[' + my_data + ']');

jsonObj.forEach(function(item,i){
  console.log(item.region + ' - ' + item.intrface);
});

Snap 假定您对 svg 有一些了解。您只需要创建 svg 元素并使用 attr 方法设置它们的样式。

基本上您将使用 line , text and rect 个元素。

api 非常简单。

要更改元素的填充颜色,请使用 fill 属性,对于描边颜色,请使用 stroke 属性。

至于 link,我不太清楚该怎么做,但您始终可以向每个元素添加点击事件,然后使用以下方法将页面重定向到某些 url:

window.location.href = 'http://example.com';

这是如何执行您想要的操作的代码示例。

const data = [{ "rec": "1", "region": "LEFT", "intrface": "Line-1" },{ "rec": "1", "region": "LEFT", "intrface": "Line-2" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-3" },{ "rec": "1", "region": "RIGHT", "intrface": "Line-4" }];

const s = Snap("#svg");
const height = 40;
const canvasWidth = 400;
const lineWidth = 180;
const rightOffset = canvasWidth/2 - lineWidth;

const leftLines = data.filter((line) => !isRightLine(line));
const rightLines = data.filter(isRightLine);

leftLines.forEach(drawLine);
rightLines.forEach(drawLine);

const numberOfLines = Math.max(leftLines.length, rightLines.length);
const rectSize = 20;
const rectangles = [];

for (let i = 0; i < numberOfLines; i++) {
    rectangles.push(drawRect(i));
}

function drawLine(data, index) {
    const {intrface} = data;
    const isRight = isRightLine(data);
    const x = isRight ? canvasWidth/2 + rightOffset : 0;
  const y = height * (index + 1);
  const stroke = isRight ? 'red' : 'black';

    const line = s.line(x, y, x + 180, y);
  line.attr({
    stroke,
    strokeWidth: 1
  });

  const text = s.text(x + 10, y - 5, intrface);

  text.attr({
    fill: stroke,
    cursor: 'pointer'
  });

  text.click(() => {
    console.log('clicked', data);

    //window.location.href = "http://whosebug.com/";
  });
}

function isRightLine({region}) {
    return region === 'RIGHT';
}

function drawRect(index) {
    const x = canvasWidth/2 - rectSize/2;
  const y = height * (index + 1) - rectSize/2;
    const rectangle = s.rect(x, y, rectSize, rectSize);

  rectangle.attr({
    fill: 'black'
  });

  console.log('rr', x, y);

  return rectangle;
}

代码笔:http://codepen.io/sielakos/pen/eZwrMj