我将 X Y Z 坐标转换为屏幕 X Y 坐标有什么问题?

2022-01-17 00:00:00 canvas javascript html html5-canvas

我正在做一个 HTML5 Canvas 演示,演示在 3D 空间中弹跳的球体.这很简单.每个球都有 X、Y 和 Z 坐标.然后将这些坐标转换为我在此处阅读的屏幕 X 和 Y 坐标.http://answers.google.com/answers/threadview/id/496030.html

I am working on a HTML5 Canvas demo of spheres bouncing in 3D space. This is very simple to do. Each ball has X, Y, and Z co-ordinates. These co-ordinates are then converted into screen X and Y co-ordinates that I read here. http://answers.google.com/answers/threadview/id/496030.html

我从上面的链接中得到的将 X Y Z 坐标转换为 X 和 Y 的公式是

The formula that I got from the above link to convert X Y Z co-ordinates into X and Y is

screenX = (depth/(Z+depth)) * X
screenY = (depth/(Z+depth)) * Y

我在这里展示了 jsFiddle 中的工作代码.http://jsfiddle.net/xeMpv/

I have put a demonstration of the working code in jsFiddle here. http://jsfiddle.net/xeMpv/

但这里有些不对劲.我得到的结果是这样的.你能告诉我我做错了什么吗?

But something is off here. The result I get looks like this. Can you tell me what I am doing wrong?

推荐答案

目前你的原点(origo)在左上角.投影 xy 以便您的原点或此处:笛卡尔坐标 [0, 0, 0] 位于屏幕中心:

Currently your origin (origo) is in the top left corner. To project x and y so that your origin, or here: the Cartesian coordinate [0, 0, 0] is in center of the screen:

f = fieldOfView / (viewDistance + z);
px = x * f + screenWidth * 0.5;
py = y * f + screenHeight * 0.5;

  • fieldOfView与焦距有关,例如128 - 256.
  • viewDistance 转换 z 值.
  • pxpy 是投影的 2D 坐标.
    • fieldOfView is related to focal distance, use for example 128 - 256.
    • viewDistance translates z values.
    • px and py are the projected 2D coordinates.
    • 如果您的所有坐标都是正的,它们将被绘制在原点的右侧/底部,因此您需要使用负值来在其左侧/顶部放置一些东西.

      If all your coordinates are positive they will be drawn on the right/bottom side of the origin so you need to use negative values to have something on the left/top side of it.

      另外:您可以用 rect() 替换线条操作,如果您将它们缓存到屏幕外画布,您可以将其blit"到主画布而不是清除和重新绘制每次都会给您带来更好的性能.

      Additionally: you can replace the line operations with rect()s and if you cache them to an off-screen canvas you can "blit" that to main canvas instead of clearing and re-drawing each time which gives you a little better performance.

相关文章