我正在尝试使用x
形状的值加上它的宽度来计算画布绘图上每个形状的标签的偏移量w
。
我只想获取x
和w
值的总和并将其用作参数,就像这样,of 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 循环的开头。看起来这应该很容易,但显然不是。任何帮助,将不胜感激。这是小提琴。我的完整代码如下。非常感谢!
<!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>