You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于GLUT/OpenGL的绘图程序绘制功能异常问题排查

问题原因及修复方案

你代码里存在以下问题导致无法正常绘制:

  • 没有配置投影/视口矩阵,默认OpenGL使用[-1,1]范围的归一化设备坐标,你直接传入0~600范围的窗口像素坐标,绝大多数点都会落在视口外无法显示
  • 初始化显示模式用了GLUT_DOUBLE双缓冲,但display函数仅调用glFlush,没有执行glutSwapBuffers交换前后缓冲,绘制内容全部存在后缓冲没有输出到屏幕
  • 定义了pointSize变量但没有调用glPointSize(pointSize)设置点大小,默认点大小仅1像素,即使坐标正确也很难观察到
  • glBegin和glEnd没有配对在同一逻辑块中,当前写法虽然暂时可运行,但后续扩展逻辑极易触发OpenGL状态错误
  • 全局变量leftBottState、xvalue、yvalue未初始化,程序启动后初始值随机,可能引发异常绘制
  • 自定义的init初始化函数从未调用,内部配置无法生效

修正后的完整代码

#include <GL/glut.h>
#include <iostream>

float pointSize = 10.0f;
bool leftBottState = false;
float xvalue = 0.0f;
float yvalue = 0.0f;

void init()
{
    glClearColor(0.0, 0.0, 0.0, 0.0);
    // 设置点大小
    glPointSize(pointSize);
    // 配置2D正交投影,把像素坐标直接映射到OpenGL坐标
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, 600, 0, 600);
    glMatrixMode(GL_MODELVIEW);
}

void dots()
{
    glBegin(GL_POINTS);
    glVertex3f(xvalue, yvalue, 0.0);
    glEnd(); // glEnd和glBegin配对调用
}

void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1, 0, 1);
    dots();
    // 双缓冲模式下替换glFlush为交换缓冲
    glutSwapBuffers();
}

void mouse(int button, int state, int x, int y)
{
    y = 600 - y;
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    {
        leftBottState = true;
    }
    else
    {
        leftBottState = false;
    }
}

void motion(int x, int y) 
{   
    if (leftBottState) 
    {
        std::cout << "LEFt bUTTON " << std::endl;
        xvalue = x;
        yvalue = y;
        glutPostRedisplay();
    }
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutInitWindowSize(600, 600);
    glutCreateWindow("test");
    // 调用初始化函数
    init();
    glutMotionFunc(motion);
    glutDisplayFunc(display);   
    glutMouseFunc(mouse);
    glutMainLoop();

    return 0;                  
}

内容的提问来源于stack exchange,提问作者derich98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:39:01