[英]In HTML5 Canvas, can I make the y axis go up rather than down?
I'm drawing a graph in Canvas and struggling with the fact that the y-axis is "backward." 我正在Canvas中绘制一个图形,并且正在努力解决y轴“向后”的问题。 The origin is in the top-left corner, and increasing values go down rather than up. 原点位于左上角,增加值下降而不是上升。
(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的坐标按照我期望的方式工作?
For more modern setup, you can use context.transform(1, 0, 0, -1, 0, canvas.height)
. 对于更现代的设置,您可以使用context.transform(1, 0, 0, -1, 0, canvas.height)
。 This flips y axis and moves the whole canvas one screenful. 这会翻转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
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。
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>
It depends on where you put the .scale I just tried this and it didn't work at first. 这取决于你把.scale放在哪里我刚刚尝试了这个并且它起初没有用。 You need to put the .scale between the moveTo(); 你需要把.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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.