javascript 在 HTML5 Canvas 中,我可以让 y 轴向上而不是向下吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4335400/
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
In HTML5 Canvas, can I make the y axis go up rather than down?
提问by Patrick McElhaney
I'm drawing a graph in Canvas and struggling with the fact that the y-axis is "backward." The origin is in the top-left corner, and increasing values go down rather than up.
我正在 Canvas 中绘制图形,并为 y 轴“向后”这一事实而苦苦挣扎。原点在左上角,增加的值会下降而不是上升。
(0,0) (x,0) (0,y) ^
+--------------> |
| |
| CANVAS | INSTEAD
| DOES THIS | OF THIS
| |
| +----------------->
(0,y) v (0,0) (x,0)
I know that I can move the origin to the bottom-left corner using translate().
我知道我可以使用 translate() 将原点移动到左下角。
context.translate(0, canvas.height);
And I know that I can invert the y-axis using scale().
而且我知道我可以使用 scale() 反转 y 轴。
context.scale(1, -1);
That seems to work, except that it causes text to appear upside-down. Is there a way to make Canvas's coordinates work the way I expect?
这似乎有效,只是它会导致文本上下颠倒。有没有办法让 Canvas 的坐标按照我期望的方式工作?
采纳答案by user5520124
For more modern setup, you can use context.transform(1, 0, 0, -1, 0, canvas.height). This flips y axis and moves the whole canvas one screenful.
对于更现代的设置,您可以使用context.transform(1, 0, 0, -1, 0, canvas.height). 这会翻转 y 轴并将整个画布移动一屏。
More on available transformations: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/transform
有关可用转换的更多信息:https: //developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/transform
回答by Skilldrick
I think you'd do much better to just get used to it. The origin is in the top left with most pixel-based video/screen APIs.
我认为你会做得更好,只是习惯了它。大多数基于像素的视频/屏幕 API 位于左上角。
回答by Rich
Plot graph_height - y.
情节graph_height - y。
eg: http://jsfiddle.net/nVUUM/
例如:http: //jsfiddle.net/nVUUM/
<canvas></canvas>
<script>
var e = document.getElementsByTagName('canvas')[0];
var c = e.getContext('2d');
function plot(x,y) {
c.fillRect(x, e.height-y, 5, 5);
}
plot(100,50);
plot(200,100);
</script>
回答by brocksprogramming
It depends on where you put the .scale I just tried this and it didn't work at first. You need to put the .scale between the moveTo();
这取决于你把 .scale 放在哪里,我刚试过这个,一开始没用。您需要将 .scale 放在 moveTo(); 之间。
ctx.arc(50,50,50,0,2*Math.PI);
ctx.moveTo(50,50);
ctx.scale(1,-1);
ctx.lineTo(50,100);
ctx.stroke();
ctx.arc(50,50,50,0,2*Math.PI);
ctx.moveTo(50,50);
ctx.scale(1,-1);
ctx.lineTo(50,100);
ctx.stroke();

