[英]How to sum the value of two array members in javascript for loop
我正在嘗試使用形狀的x
值加上寬度w
來計算畫布上每個形狀的標簽偏移量。
我只想獲取x
和w
值的總和,並將其用作ctx.fillText()
。
然后,這將使文本標簽偏移,使其位於每個shape元素的右側。
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循環的開始。 看起來這樣應該很容易,但顯然不是。 任何幫助,將不勝感激。 這是小提琴 。 我的完整代碼如下。 非常感謝!
<!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>
您正在嘗試對兩個字符串求和...首先使用排版將字符串更改為整數
var offset = Number(data[i].x) + Number(data[i].w)
data[i].x
和data[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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.