欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

九、绘制三角形

程序员文章站 2024-02-20 23:21:16
...

代码实例:


/*
 *简单绘制三角形实例
*/

#define GLEW_STATIC
#include <stdio.h>
#include <stdlib.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )  //这行是取消显示控制台

char szTitle[64] = "opengl view";

// Window dimensions    
const GLuint WIDTH = 800, HEIGHT = 600;

static void error_callback(int error, const char* description) {
	fputs(description, stderr);
}

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
	if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
		glfwSetWindowShouldClose(window, GL_TRUE);
}

//opengl 绘制
static void render(GLFWwindow * window) {

	glClearColor(0, 0, 0, 1);
	glClear(GL_COLOR_BUFFER_BIT);

	//画三角形
	glBegin(GL_TRIANGLES); //表示绘制的是三角形

	//给定三个点
	glVertex3f(WIDTH * 0.5, 0, 0);
	glVertex3f(WIDTH, HEIGHT, 0);
	glVertex3f(0, HEIGHT, 0);

	glEnd();

	glfwSwapBuffers(window);
	glfwPollEvents();
}

int main(void) {
	GLFWwindow * window;

	glfwSetErrorCallback(error_callback);

	if(!glfwInit()) return -1;
	window = glfwCreateWindow(WIDTH, HEIGHT, szTitle, NULL, NULL);
	if(!window) {
		glfwTerminate();
		exit(EXIT_FAILURE);
	}

	glfwMakeContextCurrent(window);
	glfwSetKeyCallback(window, key_callback);

	glewExperimental = GL_TRUE;
	glewInit();

	glViewport(0, 0, WIDTH, HEIGHT); //设置opengl视口 即看到的显示区域

	glMatrixMode(GL_PROJECTION); //设置当前操作的是投影矩阵列表
	glLoadIdentity(); //将投影矩阵清空成单位矩阵
	glOrtho(0, WIDTH, HEIGHT, 0, -100, 100); //产生一个新的投影矩阵并和上面的投影矩阵列表最上面单位矩阵相乘,实际上就是产生一个投影矩阵并放到投影矩阵列表的最上面 

	while(!glfwWindowShouldClose(window)) {
		render(window);
	}

	glfwDestroyWindow(window);

	glfwTerminate();
	return 0;
}

运行结果:

九、绘制三角形

相关标签: # 1.7 OpenGL