数组中有以下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绘制图像左侧的线条,以及使用上面JSON中的" region“值和”in“值绘制图像右侧的线条。
在绘制这些SVG线条时,在迭代每个JSON对象时,我还需要将"intrface“的值像label/text一样放置在每条SVG行的上方。
下面是我所要做的事情:假设我正在绘制输入(第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);
});发布于 2016-05-20 10:56:02
Snap假设对svg有一些了解。您只需创建svg元素并使用attr方法对它们进行样式设置即可。
基本上,您将使用线路、文本和矩形元素。
api非常简单。
若要更改元素的填充颜色,请使用填充属性,对于笔画颜色,请使用笔画属性。
至于链接,我不太确定如何做到这一点,但始终可以将单击事件添加到每个元素,然后使用以下方法将页面重定向到某些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://stackoverflow.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;
}Codepen:http://codepen.io/sielakos/pen/eZwrMj
https://stackoverflow.com/questions/37338219
复制相似问题