【愚公系列】2022年09月 微信小程序-WebGL立体图形的绘制

article/2025/9/21 14:07:31

文章目录

  • 前言
  • 一、webgl的使用
    • 1.立体图形的绘制
  • 二、相关包源码
  • 三、总结


前言

WebGL(全写Web Graphics Library)是一种3D绘图协议,这种绘图技术标准允许把JavaScript和OpenGL ES 2.0结合在一起,通过增加OpenGL ES 2.0的一个JavaScript绑定,WebGL可以为HTML5 Canvas提供硬件3D加速渲染,这样Web开发人员就可以借助系统显卡来在浏览器里更流畅地展示3D场景和模型了,还能创建复杂的导航和数据视觉化。显然,WebGL技术标准免去了开发网页专用渲染插件的麻烦,可被用于创建具有复杂3D结构的网站页面,甚至可以用来设计3D网页游戏等等。–百度百科

在现实中webgl的用途很多,比如医院运维网站,地铁运维网站,海绵城市,可以以三维网页形式展示出现实状态。

WebGL相关文档:http://doc.yonyoucloud.com/doc/wiki/project/webgl/webgL-fundamentals.html

在这里插入图片描述

一、webgl的使用

安装第三方包:npm i --save threejs-miniprogram

1.立体图形的绘制

import drawCube from './drawCube'Page({/*** 页面的初始数据*/data: {},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {},/*** 生命周期函数--监听页面初次渲染完成*/onReady: function () {wx.createSelectorQuery().select('#myCanvas1').node().exec((res) => {const canvas = res[0].nodeconst gl = canvas.getContext('webgl')if (!gl) {console.log('webgl未受支持');return}// 检查所有支持的扩展var available_extensions = gl.getSupportedExtensions();console.log(available_extensions);// 清除画布// 使用完全不透明的黑色清除所有图像,我们将清除色设为黑色,此时并没有开始清除gl.clearColor(0.0, 0.0, 0.0, 1.0);// 用上面指定的颜色清除缓冲区gl.clear(gl.COLOR_BUFFER_BIT);// 画的是一个正方形drawCube(gl, canvas)
})
import {mat4
} from '../../lib/gl-matrix'var cubeRotation = 0.0;//
// Start here
//
function drawCube(gl,canvas) {// Vertex shader programconst vsSource = `attribute vec4 aVertexPosition;attribute vec4 aVertexColor;uniform mat4 uModelViewMatrix;uniform mat4 uProjectionMatrix;varying lowp vec4 vColor;void main(void) {gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;vColor = aVertexColor;}`;// Fragment shader programconst fsSource = `varying lowp vec4 vColor;void main(void) {gl_FragColor = vColor;}`;// Initialize a shader program; this is where all the lighting// for the vertices and so forth is established.const shaderProgram = initShaderProgram(gl, vsSource, fsSource);// Collect all the info needed to use the shader program.// Look up which attributes our shader program is using// for aVertexPosition, aVevrtexColor and also// look up uniform locations.const programInfo = {program: shaderProgram,attribLocations: {vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),vertexColor: gl.getAttribLocation(shaderProgram, 'aVertexColor'),},uniformLocations: {projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),},};// Here's where we call the routine that builds all the// objects we'll be drawing.const buffers = initBuffers(gl);var then = 0;// Draw the scene repeatedlyfunction render(now) {now *= 0.001;  // convert to secondsconst deltaTime = now - then;then = now;drawScene(gl, programInfo, buffers, deltaTime);canvas.requestAnimationFrame(render);}canvas.requestAnimationFrame(render);
}//
// initBuffers
//
// Initialize the buffers we'll need. For this demo, we just
// have one object -- a simple three-dimensional cube.
//
function initBuffers(gl) {// Create a buffer for the cube's vertex positions.const positionBuffer = gl.createBuffer();// Select the positionBuffer as the one to apply buffer// operations to from here out.gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);// Now create an array of positions for the cube.const positions = [// Front face-1.0, -1.0,  1.0,1.0, -1.0,  1.0,1.0,  1.0,  1.0,-1.0,  1.0,  1.0,// Back face-1.0, -1.0, -1.0,-1.0,  1.0, -1.0,1.0,  1.0, -1.0,1.0, -1.0, -1.0,// Top face-1.0,  1.0, -1.0,-1.0,  1.0,  1.0,1.0,  1.0,  1.0,1.0,  1.0, -1.0,// Bottom face-1.0, -1.0, -1.0,1.0, -1.0, -1.0,1.0, -1.0,  1.0,-1.0, -1.0,  1.0,// Right face1.0, -1.0, -1.0,1.0,  1.0, -1.0,1.0,  1.0,  1.0,1.0, -1.0,  1.0,// Left face-1.0, -1.0, -1.0,-1.0, -1.0,  1.0,-1.0,  1.0,  1.0,-1.0,  1.0, -1.0,];// Now pass the list of positions into WebGL to build the// shape. We do this by creating a Float32Array from the// JavaScript array, then use it to fill the current buffer.gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);// Now set up the colors for the faces. We'll use solid colors// for each face.const faceColors = [[1.0,  1.0,  1.0,  1.0],    // Front face: white[1.0,  0.0,  0.0,  1.0],    // Back face: red[0.0,  1.0,  0.0,  1.0],    // Top face: green[0.0,  0.0,  1.0,  1.0],    // Bottom face: blue[1.0,  1.0,  0.0,  1.0],    // Right face: yellow[1.0,  0.0,  1.0,  1.0],    // Left face: purple];// Convert the array of colors into a table for all the vertices.var colors = [];for (var j = 0; j < faceColors.length; ++j) {const c = faceColors[j];// Repeat each color four times for the four vertices of the facecolors = colors.concat(c, c, c, c);// colors = colors.concat(c);// colors = colors.concat(c);// colors = colors.concat(c);// colors = colors.concat(c);}const colorBuffer = gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);// Build the element array buffer; this specifies the indices// into the vertex arrays for each face's vertices.const indexBuffer = gl.createBuffer();gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);// This array defines each face as two triangles, using the// indices into the vertex array to specify each triangle's// position.const indices = [0,  1,  2,      0,  2,  3,    // front4,  5,  6,      4,  6,  7,    // back8,  9,  10,     8,  10, 11,   // top12, 13, 14,     12, 14, 15,   // bottom16, 17, 18,     16, 18, 19,   // right20, 21, 22,     20, 22, 23,   // left];// Now send the element array to GLgl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(indices), gl.STATIC_DRAW);return {position: positionBuffer,color: colorBuffer,indices: indexBuffer,};
}//
// Draw the scene.
//
function drawScene(gl, programInfo, buffers, deltaTime) {gl.clearColor(0.0, 0.0, 0.0, 1.0);  // Clear to black, fully opaquegl.clearDepth(1.0);                 // Clear everythinggl.enable(gl.DEPTH_TEST);           // Enable depth testinggl.depthFunc(gl.LEQUAL);            // Near things obscure far things// Clear the canvas before we start drawing on it.gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);// Create a perspective matrix, a special matrix that is// used to simulate the distortion of perspective in a camera.// Our field of view is 45 degrees, with a width/height// ratio that matches the display size of the canvas// and we only want to see objects between 0.1 units// and 100 units away from the camera.const fieldOfView = 45 * Math.PI / 180;   // in radiansconst aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;const zNear = 0.1;const zFar = 100.0;const projectionMatrix = mat4.create();// note: glmatrix.js always has the first argument// as the destination to receive the result.mat4.perspective(projectionMatrix,fieldOfView,aspect,zNear,zFar);// Set the drawing position to the "identity" point, which is// the center of the scene.const modelViewMatrix = mat4.create();// Now move the drawing position a bit to where we want to// start drawing the square.mat4.translate(modelViewMatrix,     // destination matrixmodelViewMatrix,     // matrix to translate[-0.0, 0.0, -6.0]);  // amount to translatemat4.rotate(modelViewMatrix,  // destination matrixmodelViewMatrix,  // matrix to rotatecubeRotation,     // amount to rotate in radians[0, 0, 1]);       // axis to rotate around (Z)mat4.rotate(modelViewMatrix,  // destination matrixmodelViewMatrix,  // matrix to rotatecubeRotation * .7,// amount to rotate in radians[0, 1, 0]);       // axis to rotate around (Y)// Tell WebGL how to pull out the positions from the position// buffer into the vertexPosition attribute{const numComponents = 3;const type = gl.FLOAT;const normalize = false;const stride = 0;const offset = 0;gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);gl.vertexAttribPointer(programInfo.attribLocations.vertexPosition,numComponents,type,normalize,stride,offset);gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);}// Tell WebGL how to pull out the colors from the color buffer// into the vertexColor attribute.{const numComponents = 4;const type = gl.FLOAT;const normalize = false;const stride = 0;const offset = 0;gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);gl.vertexAttribPointer(programInfo.attribLocations.vertexColor,numComponents,type,normalize,stride,offset);gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);}// gl.ARRAY_BUFFER: 包含顶点属性的Buffer,如顶点坐标,纹理坐标数据或顶点颜色数据。
// gl.ELEMENT_ARRAY_BUFFER: 用于元素索引的Buffer。// Tell WebGL which indices to use to index the verticesgl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);// Tell WebGL to use our program when drawinggl.useProgram(programInfo.program);// Set the shader uniformsgl.uniformMatrix4fv(programInfo.uniformLocations.projectionMatrix,false,projectionMatrix);gl.uniformMatrix4fv(programInfo.uniformLocations.modelViewMatrix,false,modelViewMatrix);{// 6个面,12个三角形,每个三角3个顶点,共36个顶点const vertexCount = 36;const type = gl.UNSIGNED_SHORT;const offset = 0;gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);}// Update the rotation for the next drawcubeRotation += deltaTime;
}//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);// Create the shader programconst shaderProgram = gl.createProgram();gl.attachShader(shaderProgram, vertexShader);gl.attachShader(shaderProgram, fragmentShader);gl.linkProgram(shaderProgram);// If creating the shader program failed, alertif (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));return null;}return shaderProgram;
}//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {const shader = gl.createShader(type);// Send the source to the shader objectgl.shaderSource(shader, source);// Compile the shader programgl.compileShader(shader);// See if it compiled successfullyif (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));gl.deleteShader(shader);return null;}return shader;
}export default drawCube

实际效果
在这里插入图片描述

二、相关包源码

gl-matrix相关包源码链接如下:
https://download.csdn.net/download/aa2528877987/86513333

三、总结

画一个图形主要经历如下四个步骤:

  • 1.编写GLSL着色器代码,一个是顶点着色器,一个是片断着色器。
  • 2.加载着色器,组成着色器程序。
  • 3.创建缓冲区对象,填充缓冲区。
  • 4.创建摄像机透视距阵,把元件放到适当的位置。
  • 5.给着色器中的变量绑定值。
  • 6.调用gl.drawArrays,从向量数组中开始绘制。

http://chatgpt.dhexx.cn/article/ZAU9nXVt.shtml

相关文章

python写窗体程序_python写窗口

广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 最近在学习 pyqt5 gui 编程,大致路线是找了套网课《撩课-python-gui编程-pyqt5》,以梳理思维导图的形式梳理了下基础知识点以及 qtdesigner 应用流程,跳过各…

用计算机绘制图形,计算机画图——图形的变形

在画图窗口中除了可以自由地绘制图形外&#xff0c;还可以使用“画图”程序提供的各种命令对绘制的图形进行简单的变形&#xff0c;十分有趣&#xff01; 使用“画图”程序中的“翻转&#xff0f;旋转”命令&#xff0c;可以对选定的图形区域或者整幅图画进行翻转和旋转处理。 …

图形编程概念—显卡/GPU是如何工作的?

计算机显卡在设计之初主要是为了解决实时渲染三维图像的问题&#xff0c;这里的实时指的是能够以很快的速度生成图像&#xff0c;而不是显示播放已经预先录制好的视频。实时渲染对于任何一个游戏都至关重要&#xff0c;因为计算机屏幕显示的图像&#xff0c;都是对玩家操作的及…

编写python程序、输出*图形_Python用程序输出字母“C”的图案

本文主要演示Python用程序输出字母“C”的图案。 工具/原料 windows系统电脑1台 提前安装好pycharm社区免费版 方法/步骤 1 打开桌面的pycharm程序&#xff1b; 2 依次点击 file > New Project 新建一个代码目录&#xff1b; 3 依次点击 New > Python File 新建一…

转载:opencv-9-图像噪声以及评估指标 PSNR 与SSIM

本文转自博客园博主SChen1024的博文&#xff1a;opencv-9-图像噪声以及评估指标 PSNR 与SSIM 开始之前# 我们在将 opencv 的图像显示在了 qt 的label 上, 我们能够将图显示在label 上, 用于显示我们的算法, 我们在 opencv 上一篇文章中介绍了 opencv 的核操作, 我们这里就要进入…

三维图形程序设计

三维图形程序设计 基础知识计算机图形学概述图形与图像图形流水线图形开发库GPU OpenGL编程OpenGL的功能OpenGL的两种编程模式OpenGL相关的库OpenGL基本语法程序流程 变换(Transformation)变换的步骤几何变换投影变换视口变换 光照光照明模型phong模型Blinn-Phong光照模型openg…

Python图像处理

一、简介 实现计算机视觉任务的过程中&#xff0c;不可避免地需要对图像进行读写操作以及图像预处理操作&#xff0c;下面介绍两个常用的Python图像处理库&#xff1a;OpenCV和Pillow。 OpenCV全称是由英特尔公司资助的开源计算机视觉库。 它由一系列C函数和少量C&#xff0b…

OpenCV-Python图形图像处理:制作雪花飘落特效

☞ ░ 老猿Python博文目录&#xff1a;https://blog.csdn.net/LaoYuanPython ░ 一、引言 前几天有博友咨询&#xff0c;能否在视频中实现雪花飘落的效果&#xff0c;答案是肯定的。老猿前天简单构思了一下&#xff0c;利用周末时间&#xff0c;使用OpenCV-Python通过图像循环…

图像处理程序的设计与实现

一、要求&#xff1a; 1.利用Qt和QPainter实现一个图像处理程序&#xff0c;有菜单栏、工具栏和状态栏 2.有图像选择对话框&#xff0c;以选择和读取图像 3.状态栏显示图像的像素&#xff0c;位深&#xff0c;导入图像的路径和鼠标所在点的像素点坐标 4.可以对图像缩放&#xf…

C#图形化程序设计知识总结

图形化程序设计 用可视化的界面进行程序设计 逃出控制台丑丑的黑框 知识导图 图为图形化程序设计的内容清单 Windows窗体程序设计 窗体设计 窗体是一个窗口或对话框&#xff0c;是存放各种控件的容器&#xff0c;可用来向用户显示信息 一个Windows应用程序可以包含多个窗体 …

python 图像分割_5行Python代码实现图像分割的步骤详解

众所周知图像是由若干有意义的像素组成的&#xff0c;图像分割作为计算机视觉的基础&#xff0c;对具有现有目标和较精确边界的图像进行分割&#xff0c;实现在图像像素级别上的分类任务。 图像分割可分为语义分割和实例分割两类&#xff0c;区别如下&#xff1a; 语义分割&am…

台式计算机驱动程序未被安装,计算机图形驱动程序安装失败的原因及其解决方法...

由于许多问题&#xff0c;兼容性和数字签名&#xff0c;计算机图形驱动程序可能会失败. 很有可能没有启用Windows安装程序服务. 每个问题都有不同的解决方案. 如何确定问题的原因&#xff0c;可以借用软件进行检测&#xff0c;也可以尝试一种然后修复. 如果由于Windows Install…

LabVIEW程序框图保存为图像

LabVIEW程序框图保存为图像 想将LabVIEW程序框图保存为标准图像文件&#xff0c;以便可以在LabVIEW之外查看或在文档中使用。如何将程序框图生成为图像&#xff1f; 可以通过打印VI或以编程方式获取LabVIEW程序框图图像。 要打印VI&#xff0c;请使用以下步骤&#xff1a; …

Python图形绘制程序设计

第1关:绘制多边形 任务描述 本关任务:依照案例教程例6-2,用多边形函数绘制各种多边形图形。 编程要求 根据提示,在右侧编辑器补充代码。 测试说明 平台会对你编写的代码进行测试: 开始你的任务吧,祝你成功! 第2关:绘制五角星图形 任务描述 本关任务:绘制一个黄色…

升级计算机的图形卡和驱动程序,如何升级计算机图形卡,计算机图形卡升级方法图...

[哈哈IT网络中关村显卡]如何升级计算机显卡&#xff0c;通常我们会对显卡驱动程序做进一步的升级&#xff0c;这有助于提高显卡的性能&#xff0c;达到达到显卡升级的目的. 显卡驱动程序升级使计算机显示效果更好&#xff0c;显示效果也得到了提高. 下面介绍如何升级计算机图形…

计算机图形驱动程序原理,您知道更新计算机图形驱动程序的作用吗?怎么做

购买或使用计算机时&#xff0c;为了获得更好的视觉体验并避免显示的AV质量&#xff0c;我们通常在选择时安装独立的显卡&#xff01;使用计算机时&#xff0c;有时第三方软件会提示您更新计算机图形驱动程序&#xff0c;但有时却没有&#xff01;更新计算机图形驱动程序有什么…

VTK图形图像开发进阶-学习笔记 01 VTK概述

1.1 VTK概述 1.1.1VTK是什么 1.1.2VTK能做什么 1.1.3如何获取VTK源码 略 1.1.4 VTK学习资源 略 1.2 VTK编译安装 略 1.3创建一个简单的VTK程序 步骤一&#xff1a;创建目录A&#xff1a; D:\VTK\example\Chap01 步骤二&#xff1a;在目录A中创建txt文件&#xff1a;CMa…

用Java完成图形图像绘制

我们要来图形图像的处理&#xff0c;目标就是滑动鼠标绘制一根直线&#xff0c;绘制一个矩形&#xff0c;绘制一个圆&#xff0c;并且绘制任意的一个三角形&#xff0c;和任意的一个等腰三角形 我们先创建一个DrawPad类&#xff0c;在这个类里面完成一些操作 步骤1、创建一个…

图形图像学习随笔:计算机图形学的一些基本概念

本文内容摘抄于&#xff1a;《计算机图形学的概念》 一、计算机图形学的范畴 1、图形主要分为两类&#xff0c;一类是基于线条信息表示的&#xff0c;如工程图、等高线地形图、曲面的线框图等&#xff1b;另一类是明暗图&#xff0c;也就是通常所说的真实感图形&#xff1b; …

升级计算机的图形卡和驱动程序,驱动程序向导如何更新图形卡驱动程序?更新图形驱动程序方法说明...

有许多用户使用驱动程序向导&#xff0c;并且一些新用户不清楚更新图形驱动程序的教程. 今天&#xff0c;我将带给您有关更新图形驱动程序的教程. 希望它能对您有所帮助. 我们首先打开计算机上已安装的驱动程序向导软件&#xff0c;然后进入软件&#xff0c;然后单击页面“立即…