javascript 将画布原点设置为左下角

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7707286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:01:39  来源:igfitidea点击:

Set canvas origin to the lower-left corner

javascripthtmlcanvas

提问by spiroski

Is there a way to set the origin to lower-left of the canvas? I tried scaling by −1 but after that everything is upside down. I need to make something like a coordinate system but only with the positive part (first quadrant). So I need it to start with 0.0 at down-left corner.

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

回答by icktoofay

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

See a demo on JSFiddle.

请参阅 JSFiddle 上的演示。

回答by Simon Sarris

is there a way to set the origin to lower-left of the canvas?

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

Not quite the way you'd like, no. The best you can do there is what icktoofay said.

不完全是你想要的方式,不。你能做的最好的事情就是 icktoofay 所说的。

That being said it isn't too hard to make a function to convert between one system and the other. For example:

话虽如此,制作一个在一个系统和另一个系统之间转换的函数并不难。例如:

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

So you'd write:

所以你会写:

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

例子

In any case, I'd strongly suggest that if you are at all able to just get used to screen coordinates. It will save you from loads of headaches in the future if you don't always have to account for this little difference.

在任何情况下,如果您完全能够习惯屏幕坐标,我强烈建议您。如果您不必总是考虑到这个微小的差异,它将使您免于未来的大量头痛。

回答by Asyl

One of the easiest and correct ways is to use ctx.transform() method documentation is here

最简单和正确的方法之一是使用 ctx.transform() 方法文档在这里