1

moveTo() の後で実際の描画カーソル位置を取得する方法がわかりません。私のコードをチェックしてください:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.moveTo(10, 20);
// here i want to get from "ctx" actual offset
ctx.lineTo(20,30);
ctx.closePath();

独自の変数 offsetX、offsetY にオフセットを保存する方法はありますか?

4

1 に答える 1

2

相対パスコマンドがたくさんあり、それらを移動したいという意味だと思います。

たとえば、左上に三角形を描くには、次のように記述します。

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,0);
ctx.lineTo(50,100);
ctx.closePath(); // makes the last line for you
ctx.stroke();

では、同じパスを使用したいが、代わりに(175、175)で始まる三角形を描画したい場合はどうでしょうか。moveTo後続のすべての描画コマンドを変更する代わりに、コンテキストを変換するだけです。

ctx.save();
ctx.translate(175, 175);

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,0);
ctx.lineTo(50,100);
ctx.closePath(); // makes the last line for you
ctx.stroke();

// save/restore lets you undo the translation so the next object starts at (0,0)
// you could just call ctx.translate(-175, -175); at the end instead though
ctx.restore(); 

コンテキストを変換すると、描画サーフェスの原点が変更され、すべての座標を(一時的かどうかに関係なく)一緒に移動できるようになります。これは、一連のパスを定義し、を使用してあらゆる場所で同じコマンドを使用してそれらを再描画できることを意味しますctx.translate

ここで両方の三角形を参照してください。

http://jsfiddle.net/qzYFC/

于 2012-11-29T23:31:20.253 に答える