官术网_书友最值得收藏!

WebGL coordinate system versus 2D canvas

With WebGL, the center of the canvas element is the origin point (0,0). Positive Y is up, whereas Positive X is to the right. This is a bit more intuitive for someone who has never worked with 2D graphics, as it is similar to quadrants in coordinate geometry, which we learned about in grade school. With the 2D canvas, you are always working with pixels, and there are no negative numbers that appear on the canvas:

When you called drawImage, the X and Y coordinates were where the top left corner of the image would draw. WebGL is a bit different. Everything is using geometry, and both a vertex and a pixel shader are required. We convert the image into a texture and then stretch it over the geometry so that it's displayed. Here is what the WebGL coordinate system looks like:

If you want to place an image at a specific pixel location on the canvas, you have to know the width and height of your canvas. The center point of your canvas is (0,0), the Top left corner is (-1, 1), and the Bottom right corner is (1, -1). So, if you want to place an image at x=150, y=160 you need to use the following equation to find the WebGL x coordinate:

 webgl_x = (pixel_x - canvas_width / 2) / (canvas_width / 2)

So, for a pixel_x position of 150, we have to subtract 400 from 150 to get -250. Then, we have to divide -250 by 400, and we would get -0.625. We have to do something similar to get the y coordinate for WebGL, but the sign of the axes are flipped, so instead of what we did for the pixel_x value, we need to do the following:

((canvas_height / 2) - pixel_y) / (canvas_height / 2)

By plugging in the values, we get ((600 / 2) - 160) / (600 / 2) or (300 - 160) / 300 = 0.47.

I am skipping a lot of information about WebGL to simplify this explanation. WebGL is not a 2D space, even though I am treating it as a 2D space in this example. Because it is a 3D space, the size of the canvas in units is based on a view area known as clip space. Mozilla has an excellent article on clip space if you would like to learn more: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_model_view_projection.
主站蜘蛛池模板: 闽侯县| 许昌市| 郁南县| 微山县| 巢湖市| 房山区| 罗山县| 成安县| 安顺市| 阜平县| 广饶县| 庆安县| 云霄县| 瓮安县| 云林县| 福州市| 封开县| 炉霍县| 长顺县| 墨竹工卡县| 石城县| 安阳县| 盐边县| 玉林市| 合山市| 南召县| 应城市| 马鞍山市| 浦江县| 松滋市| 西藏| 奉新县| 铁力市| 巍山| 彰化县| 喜德县| 上栗县| 浑源县| 麟游县| 恩施市| 清原|