我假設你的意思是你有一堆相對路徑命令,你想移動它們。
例如,在繪製三角形的左上方你可以這樣寫:
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/
完美,這正是我需要的。謝謝你的幫助 ! –