2012-11-29 181 views
1

我無法知道如何在moveTo()之後獲取實際的繪圖光標位置。看看我的代碼:HTML5畫布:繪圖光標的位置

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?

回答

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/

+0

完美,這正是我需要的。謝謝你的幫助 ! –