Computer Graphics – 12. Color Freehand Drawing

[wpdm_package id=’1233′]
Sample Input – Write a freehand drawing program so that drawing color change based on key pressed. It should seem that drawing brush has square shape. Right click should clear the screen. The window should have resize abilities.
Sample Output –Color_Freehand_Drawing

[sourcecode lang=”cpp”]
#include<GL/glut.h>
#include<cmath>
#include<cctype>

GLint screen_height=600;
GLint screen_width=600;
int brush_size=10;

void free_dots(void){
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}

void point(GLint x, GLint y){
glBegin(GL_POINTS);
glColor3f(0,0,0);
glVertex2d(x,y);
glEnd();
glFlush();
}

void reshape(GLsizei w, GLsizei h){
screen_width=w;
screen_height=h;

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,w,0,h);
glViewport(0,0,w,h);
}

void my_mouse(int button, int state, int x, int y){

if((button==GLUT_LEFT_BUTTON) && (state==GLUT_DOWN)){
point(x,screen_height-y);
}
else if((button==GLUT_RIGHT_BUTTON)&&(state==GLUT_DOWN)){
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
}

void keyboard(unsigned char key, int x, int y){
if(tolower(key)==’r’){
glBegin(GL_POINTS);
glColor3f(1.0,0.0,0.0);
}
else if(tolower(key)==’g’){
glColor3f(0,1.0,0);
}
else if(tolower(key)==’b’){
glColor3f(0,0,1.0);
}
else if(tolower(key)==’y’){
glColor3f(1.0,1,0);
}
else if(tolower(key)==’m’){
glColor3f(1,0,1);
}
else if(tolower(key)==’c’){
glColor3f(0,1,1);
}
else{
glColor3f(1,1,1);
}

}

void moving_cursor(int x, int y){
GLint mx=x, my=screen_height – y;
glRecti(mx, my, mx+brush_size, my+brush_size);
glFlush();
}
void init(){
glClearColor(1.0f,1.0f,1.0f,0.0f);
glColor3f(0.0f,0.0f,0.0f);
glPointSize(1);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,screen_width,0,screen_height);
}

int main(int argc,char **argv){
glutInit(&argc,argv);
glutInitWindowSize(600,600);
glutInitWindowPosition(60,60);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutCreateWindow("Color Freehand Drawing");

glutDisplayFunc(free_dots);
glutMouseFunc(my_mouse);
glutKeyboardFunc(keyboard);
glutMotionFunc(moving_cursor);

glutReshapeFunc(reshape);

init();
glutMainLoop();
}
[/sourcecode]

To compile the above program in ubuntu terminal –
# g++ -lGL -lGLU -lglut Color_Freehand_Drawing.cpp
# ./a.out

Leave a Reply

Your email address will not be published. Required fields are marked *