如何在javascript for循环中求和两个数组成员的值

时间:2013-10-31 17:15:47

标签: javascript arrays canvas sum

我正在尝试使用形状的x值及其宽度w来计算画布上每个形状的标签偏移量。

我只想得到xw值的总和,并将其用作ctx.fillText()的参数。

然后,这将偏移文本标签,使其位于每个形状元素的右侧。

ctx.fillText(data[i].name, +data[i].x + data[i].w, +data[i].y + 15)

我有一个数组:

var data = [
    {"name": "Free-OH", "x": "270", "y": "20", "w": "20", "h": "20", "color": "blue"},
    {"name": "Bonded OH", "x": "280", "y": "50", "w": "58", "h": "20", "color": "green"},
    {"name": "-C=-CH", "x": "310", "y": "80", "w": "20", "h": "20", "color": "purple"}  
];

我在JavaScript for循环中使用的各种值。一切正常,直到我尝试使用data[i].x + data[i].w的值计算标签的偏移量。

这似乎不起作用,也没有创建像

这样的变量

var offset = data[i].x + data[i].w

在for循环的开头

。看起来这应该很简单,但显然不是。任何帮助,将不胜感激。这是fiddle。我的完整代码如下。非常感谢!

<!DOCTYPE html>
<html>
<head>
<title>Wavelength to Compound</title>
<meta charset="utf-8" />
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1/
jquery.min.js"></script>
<script>
$(document).ready(function() {
var canvas = document.getElementById("FirstCanvas");
var ctx = canvas.getContext("2d");
ctx.strokeRect(5, 5, 2990, 240);
ctx.strokeStyle = "#DDDDDD";
ctx.beginPath();
ctx.moveTo(5, 210);
ctx.lineTo(2995, 210);
ctx.closePath();
ctx.stroke();
ctx.lineWidth = 1;
ctx.font = "14pt Arial";
ctx.fillText("0", 10, 235); 
ctx.fillText("30", 2970, 235);


var data = [{"name": "Free-OH", "x": "270", "y": "20", "w": "20", "h": "20", "color": "blue"},
            {"name": "Bonded OH", "x": "280", "y": "50", "w": "58", "h": "20", "color": "green"},
            {"name": "-C=-CH", "x": "310", "y": "80", "w": "20", "h": "20", "color": "purple"}  
];

for (var i = 1; i < 150; i++){
    ctx.beginPath();
    ctx.moveTo(i*20, 210);
    ctx.lineTo(i*20, 5);
    ctx.closePath();
    ctx.stroke();
}

for (var i = 1; i < 30; i++){
    ctx.lineWidth = 1;
    ctx.fillText(i/2, i*100-7.5, 235);
}

for (var i = 0; i < data.length; i++){
ctx.fillStyle = data[i].color;
ctx.fillRect(data[i].x, data[i].y, data[i].w, data[i].h);
ctx.fillText(data[i].name, +data[i].x + data[i].w, +data[i].y + 15);
}


});
</script>
</head>
<body>
<canvas id="FirstCanvas" width="3000" height="250">
<p>Wavelength to Compound</p>
<div id="content"><div/>
</canvas>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您正在尝试对两个字符串求和...首先使用排版

将字符串更改为整数
var offset = Number(data[i].x) + Number(data[i].w)

答案 1 :(得分:0)

data[i].xdata[i].w是字符串。要将它们添加到一起,请执行以下操作之一:

+data[i].x + +data[i].w;

parseInt(data[i].x, 10) + parseInt(data[i].w, 10);

Number(data[i].x) + Number(data[i].w);

Fiddle