我在数组中有以下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,图像左侧的线条以及图像右侧的线条使用&#34进行绘制;区域"价值和"介入"上述JSON中的值。
绘制这些SVG线时,我还需要在这些SVG线的上方放置" intrface"的值。像标签/文本一样,我迭代每个JSON对象。
只是为了帮助看看我所追求的东西,假设我正在绘制输入(Line-1和Line-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);
});
答案 0 :(得分:2)
Snap假设有关svg的一些知识。您只需要创建svg元素并使用attr方法设置它们的样式。
api非常简单。
更改元素使用填充属性的填充颜色以及笔触颜色使用笔触属性。
至于链接,我不太清楚如何做到这一点,但你总是可以为每个元素添加click事件,然后使用以下命令将页面重定向到某个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;
}