将画布原点设置为左下角

时间:2011-10-09 23:29:07

标签: javascript html5 canvas

嘿伙计们有没有办法将原点设置在画布的左下角?我尝试按-1缩放,但之后一切都是颠倒的。我需要制作类似坐标系的东西,但只能使用正面部分(第一象限)。所以我需要它从左下角的0.0开始。

3 个答案:

答案 0 :(得分:18)

ctx.translate(0, canvas.height);
ctx.scale(1, -1);

<强> See a demo on JSFiddle.

答案 1 :(得分:3)

  

有没有办法将原点设置为画布的左下角?

不是你喜欢的方式,不。你可以做的最好的是icktoofay所说的。

据说,在一个系统和另一个系统之间进行转换并不太难。例如:

// Given an X,Y in 1st quadrant cartesian coordinates give the corresponding screen coordinate
function cartToScreen(px, py) {
  return [px, -py + HEIGHT];
};

所以你要写:

var coords = cartToScreen(50,50);
// draws 50 pixels from the bottoom instead of 50 pixels from the top
ctx.fillText("lalala", coords[0], coords[1]);

Example

无论如何,我强烈建议你,如果你能够习惯屏幕坐标。如果你不总是要考虑到这个小小的差异,它将在未来避免你的头痛。

答案 2 :(得分:0)

一种最简单正确的方法是使用ctx.transform()方法documentation is here