How to make a window that swaps between colors using OpenGL with GLFW and Glad in C++

1 Answer

0 votes
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>

int main()
{
	// Initialize GLFW
	glfwInit();

	// Use OpenGL 4.6
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
	
	// Use the CORE profile = only the modern functions
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	// Create a GLFWwindow object of 800 by 600 pixels
	GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL", NULL, NULL);
	if (window == NULL) {
		std::cout << "Failed to create GLFW window" << std::endl;
		glfwTerminate();
		return -1;
	}

	// Makes the context of the specified window current
	glfwMakeContextCurrent(window);

	// Load GLAD to configure OpenGL
	gladLoadGL();

	// Specify the viewport of OpenGL in the Window - from x = 0, y = 0, to x = 800, y = 600
	glViewport(0, 0, 800, 600);

	float prev_time = float(glfwGetTime());
	float color = 0.0f; 

	while (!glfwWindowShouldClose(window)) {
		float time = float(glfwGetTime());
		if (time - prev_time >= 0.3f) {
			color += 0.3f;
			prev_time = time;
		}
		glClearColor(float(sin(color)), float(cos(color)), float(tan(color)), 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);
		
		glfwSwapBuffers(window);

		glfwPollEvents();
	}

	// Delete the window before ending the program
	glfwDestroyWindow(window);
	
	// Terminate GLFW before ending the program
	glfwTerminate();

	return 0;
}



/*
run:



*/

 



answered Mar 30, 2025 by avibootz
edited Mar 30, 2025 by avibootz
...