对于没有经验的编码我真的很陌生,尝试使用Node-Red Template节点来创建HTML中一些简单2D坐标的可视化表示。首先,这是我第一次使用HTML和Mustache,所以这些让我感到困惑。我作为msg.payload的输入是一个JSON对象数组(如果我已经正确理解),在那些JSON中我存储了X和Y坐标,用于绘制代表项目的点。这是我的模板节点atm的代码:
<!DOCTYPE html>
<html>
<title>Factory floor map</title>
<h><b>Factory floor map</b></h>
<script type = "text/javascript">
function draw()
{
var canvas = document.getElementById("canvas");
if (null==canvas || !canvas.getContext) return;
var axes={}, ctx=canvas.getContext("2d");
axes.y0 = 100; // x0 pixels from left to x=0
axes.x0 = 100; // y0 pixels from top to y=0
axes.scale = 40; // 40 pixels from x=0 to x=1
axes.doNegativeX = false;
showAxes(ctx,axes);
plotItems(ctx,axes);
}
function plotItems(ctx,axes)
{
var ID = 0001;
for(var i = 0; i < **What here**; i++)
{
var X = axes.x0 + axes.scale*{**What here**};
var Y = axes.y0 + axes.scale*{**What here**};
drawItem(ID,X,Y,ctx,axes);
}
}
function drawItem(ID,X,Y,ctx,axes)
{
var radius = 25;
ctx.beginPath();
ctx.arc(Y, X, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = '#003300';
ctx.stroke();
}
function showAxes(ctx,axes)
{
var y0=axes.y0, w=ctx.canvas.width;
var x0=axes.x0, h=ctx.canvas.height;
var xmin = axes.doNegativeX ? 0 : x0;
ctx.beginPath();
ctx.strokeStyle = "rgb(128,128,128)";
ctx.moveTo(x0,y0); ctx.lineTo(w,y0); // Y axis
ctx.moveTo(x0,y0); ctx.lineTo(x0,h); // X axis
ctx.stroke();
}
</script>
<body onload="draw()">
<canvas id="canvas" width="1600" height="800"></canvas>
</body>
</html>
我可以在PlotItems()函数中使用例如{{#payload.2}} {{X}} {{/ payload.2}}从我的数组中找到单个值,但我希望能够逐个对象地遍历整个数组。
请告诉我如何以最简单的方式解决这个问题。
为了澄清,这里是msg.payload,它是我的Template节点的输入,我希望能够使用X和Y值:
[ { "_id": "55c099d9067c061d00ff462d", "ID": "0001 ", "X": "100 ", "Y": "4 ", "mass": "10 " }, { "_id": "55c09850067c061d00ff4623", "ID": "0004 ", "X": "15 ", "Y": "5 ", "mass": "10 " }, { "_id": "55c0aaa8067c061d00ff4630", "ID": "5 ", "X": "1 ", "Y": "34 ", "mass": "85 " }, { "_id": "55c0ab78067c061d00ff4631", "ID": "moottori ", "X": "4 ", "Y": "6 ", "mass": "85 " }, { "_id": "55c0b1a7067c061d00ff4645", "ID": "Hannes ", "X": "65 ", "Y": "74.5775 ", "mass": "80 " }, { "_id": "55c1a1e6067c061d00ff4657", "ID": "Roope ", "X": "69 ", "Y": "4 ", "mass": "85 " }, { "_id": "55c1a8b5067c061d00ff4661", "ID": "Roope_2 ", "X": "1 ", "Y": "1 ", "mass": "85 " }, { "_id": "55c1f832067c061d00ff4666", "ID": "Pasi ", "X": "1 ", "Y": "1 ", "mass": "85 " } ]
答案 0 :(得分:1)
Mustache对于填充这样的代码并不是很好,但你可以尝试这样的东西
...
function plotItems(ctx,axes)
{
var ID = 0001;
var X,Y;
{{#payload}}
X = axes.x0 + axes.scale*{{X}};
Y = axes.y0 + axes.scale*{{Y}};
drawItem(ID,X,Y,ctx,axes);
{{/payload}};
}
...