Javascript 为什么该着色器圆比通过的半径小得多?

Javascript 为什么该着色器圆比通过的半径小得多?,javascript,math,shader,webgl,Javascript,Math,Shader,Webgl,我正在开发一个GLSL着色器,它根据给定的中心位置和半径绘制一个圆。由于某种原因,我不明白,圆的半径与我经过的不匹配。也就是说,当我将100传递给u\u半径时,半径反而是56。我试着将着色器中的值加倍,虽然接近,但仍然有点不准确。有人知道是什么导致了这种差异吗 precision mediump float; varying vec4 v_pos; uniform mat3 u_matrix; uniform vec2 u_center; // the center of the circl

我正在开发一个GLSL着色器,它根据给定的中心位置和半径绘制一个圆。由于某种原因,我不明白,圆的半径与我经过的不匹配。也就是说,当我将
100
传递给
u\u半径
时,半径反而是
56
。我试着将着色器中的值加倍,虽然接近,但仍然有点不准确。有人知道是什么导致了这种差异吗

precision mediump float;

varying vec4 v_pos;

uniform mat3 u_matrix;
uniform vec2 u_center; // the center of the circle in world coordinates

uniform float u_aspect; // aspect ratio. 1.7778 for my monitor (1920x1080)
uniform float u_radius; // radius. passing in 100

uniform vec2 u_canvasSize; // [ 1920, 1080 ]

void main() {
  vec4 c = vec4((u_matrix * vec3(u_center, 1)).xy, 0, 1); // center

  vec2 onePix = vec2(1.0, 1.0) / u_canvasSize; // the size of one pixel in clip-space

  float onePixLength = sqrt(onePix.x * onePix.x + onePix.y * onePix.y); // magnitude of one pixel

  float r = onePixLength * u_radius; // radius converted to clip-space

  vec2 dist = (v_pos.xy - c.xy) * vec2(u_aspect, 1.0); // distance from center to current shader point

  if (dist.x * dist.x + dist.y * dist.y > r * r) {
    discard;
  }

  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}

这是因为标准化设备空间坐标在[-1.0,1.0]范围内。因此,在计算像素大小时缺少因子2:

vec2onepix=vec2(1.0,1.0)/u_画布尺寸

vec2 onePix=vec2(2.0)/u_画布尺寸;
此外,您需要计算像素的边长,而不是对角线长度。宽度(x尺寸)按纵横比缩放。因此,您需要计算像素的高度:

float onePixLength=sqrt(onePix.x*onePix.x+onePix.y*onePix.y)

float onePixLength=onePix.y;

注意,
onePix.x*u_方面
等于
onePix.y

谢谢您的回复。嗯,这很接近,但还是不太正确。也就是说,如果半径为
250
,则测量的渲染半径为
279
。我想知道是什么造成了这种差异?@RyanPeschel当然,因为你计算的是对角线的长度,而不是像素的边长。哦,我现在明白了。谢谢这就解决了问题