Reputation:
I am making a basic OpenGL program which like PAINT program on windows.
Description: If I drag the mouse on the window screen then after I release the button(left) a consecutive points should appear that shows the path of dragging the mouse.
My code just works with a point on screen. I want to draw points such as line but I have no idea what I do.
Here is my code:
#include <windows.h>
#include <math.h>
#include <gl/glut.h>
#include <gl/gl.h>
void myDisplay(void) {
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void myMouse(int button, int state, int x, int y)
{
int yy;
yy = glutGet(GLUT_WINDOW_HEIGHT);
y = yy - y; /* In Glut, Y coordinate increases from top to bottom */
glColor3f(1.0, 0, 0);
if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
{
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
glFlush();
}
void myInit(void)
{
glClearColor(1.0f, 1.0f, 1.0f, 0.0);
glColor3f(1.0f, 1.0f, 1.0f);
glPointSize(5.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640, 480);
glutInitWindowPosition(100, 150);
glutCreateWindow("Draw Pixel");
glutDisplayFunc(myDisplay);
glutMouseFunc(myMouse);
/*glutMotionFunc(myPressedMove);*/
myInit();
glutMainLoop();
}
Upvotes: 0
Views: 1981
Reputation: 52082
Append mouse coordinates to an array in glutMouseFunc()
, issue a glutPostRedisplay()
, and draw array in glutDisplayFunc()
:
#include <gl/glut.h>
#include <vector>
std::vector< float > points;
void myMouse(int button, int state, int x, int y)
{
int yy;
yy = glutGet(GLUT_WINDOW_HEIGHT);
y = yy - y; /* In Glut, Y coordinate increases from top to bottom */
if( (button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN) )
{
points.push_back(x);
points.push_back(y);
}
glutPostRedisplay();
}
void myDisplay(void)
{
glClearColor(1.0f, 1.0f, 1.0f, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPointSize(5.0);
glBegin(GL_POINTS);
glColor3f(1.0f, 1.0f, 1.0f);
for (size_t i = 0; i < points.size(); i += 2)
{
glVertex2i( points[i], points[i+1] );
}
glEnd();
glFlush();
}
void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640, 480);
glutInitWindowPosition(100, 150);
glutCreateWindow("Draw Pixel");
glutDisplayFunc(myDisplay);
glutMouseFunc(myMouse);
glutMainLoop();
}
Upvotes: 1