x
形状の値とその幅を使用して、キャンバス描画上の各形状のラベルのオフセットを計算しようとしていますw
。
x
とのw
値の合計を取得し、それをパラメーターとして使用したいだけです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>