0

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

我只想获取xw值的总和并将其用作参数,就像这样,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>
4

2 回答 2

0

您正在尝试对两个字符串求和...首先使用排版将字符串更改为整数

var offset = Number(data[i].x) + Number(data[i].w)
于 2013-10-31T17:20:03.013 回答
0

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);

小提琴

于 2013-10-31T17:20:38.287 回答