文章目录

  • 前言
  • 一、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 drawRectangle from './draw-rectangle'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);// 画的是一个正方形drawRectangle(gl)
})
import {mat4
} from '../../lib/gl-matrix'function drawColorRectangle(gl) {// 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 program// 每个片段只是根据其相对于顶点的位置得到一个插值过的颜色,而不是一个指定的颜色值。// lowp表示低精度// lowp, mediump和highpconst 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);// Draw the scenedrawScene(gl, programInfo, buffers);
}//
// initBuffers
//
// Initialize the buffers we'll need. For this demo, we just
// have one object -- a simple two-dimensional square.
//
function initBuffers(gl) {// Create a buffer for the square's 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 square.const positions = [1.0,  1.0,  0.0,-1.0, 1.0,  0.0,1.0,  -1.0, 0.0,-1.0, -1.0, 0.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 vertices// 此数组中包含四组四值向量,每一组向量代表一个顶点的颜色。
var colors = [1.0,  1.0,  1.0,  1.0,    // white1.0,  0.0,  0.0,  1.0,    // red0.0,  1.0,  0.0,  1.0,    // green0.0,  0.0,  1.0,  1.0,    // blue
];const colorBuffer = gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);return {position: positionBuffer,color: colorBuffer,};
}//
// Draw the scene.
//
function drawScene(gl, programInfo, buffers) {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 translate// 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);}// 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);{const offset = 0;const vertexCount = 4;gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);}
}//
// 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 drawColorRectangle

实际效果

二、相关包源码

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

三、总结

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

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

【愚公系列】2022年09月 微信小程序-WebGL画渐变色正方形相关推荐

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

    文章目录 前言 一.webgl的使用 1.立体图形的绘制 二.相关包源码 三.总结 前言 WebGL(全写Web Graphics Library)是一种3D绘图协议,这种绘图技术标准允许把JavaS ...

  2. 【愚公系列】2022年09月 微信小程序-WebGL纹理材质的使用

    文章目录 前言 一.webgl的使用 1.立体图形的绘制 二.相关包源码 三.总结 前言 WebGL(全写Web Graphics Library)是一种3D绘图协议,这种绘图技术标准允许把JavaS ...

  3. 【愚公系列】2022年09月 微信小程序-微信小程序实现网页一键登录功能

    文章目录 前言 一.微信小程序实现网页一键登录功能 1.旧版登录方法 2.新版登录方法 二.相关第三方包源码 前言 如果微信小程序要获取微信登录的用户信息,需要拿到code去后台换取用户信息,具体步骤 ...

  4. 【愚公系列】2022年09月 微信小程序-webview内嵌网页的授权认证

    文章目录 前言 一.webview内嵌网页的授权认证 1.内嵌页面 2.登录页面 二.web端相关函数 1.判断是否是小程序环境 前言 随着微信小程序的广泛应用,小程序的用户越来越多,但受其小程序体积 ...

  5. 【愚公系列】2022年09月 微信小程序-图片加载和全屏适配问题

    文章目录 前言 一.图片加载 二.适配机型实现全屏背景图 前言 在使用图片问题中可能会遇到各种各样的问题,比如图片加载不出来,图片显示在不同机型效果不同,图片加载展示问题等等. 微信小程序image相 ...

  6. 【愚公系列】2022年09月 微信小程序-自定义导航栏功能的实现

    文章目录 前言 一.自定义导航栏功能的实现 1.组件的封装 2.使用 前言 导航栏是指位于页面顶部或者侧边区域的,在页眉横幅图片上边或下边的一排水平导航按钮,它起着链接站点或者软件内的各个页面的作用. ...

  7. 【愚公系列】2022年09月 微信小程序-Page页面扩展

    文章目录 前言 一.Page页面扩展 1.组件的封装和引用 2.页面使用 3.效果 二.其他相关封装 1.pop-up组件 2.LoginPanel组件 3.LoginPanel组件 前言 在小程序日 ...

  8. 【愚公系列】2022年09月 微信小程序-图片懒加载功能实现

    文章目录 前言 一.官方图片的懒加载 1.wxml 2.js 3.css 4.效果 二.第三方包实现图片的懒加载 1.安装第三方包 2.组件引用 3.wxml 4.js 5.css 6.效果 前言 大 ...

  9. 【愚公系列】2022年09月 微信小程序-three.js绘制正方体

    文章目录 前言 一.Three.js的使用 1.正方体的绘制 二.正方体相关js文件 三.效果图 四.总结 前言 Three.js 是一款运行在浏览器中的 3D 引擎,你可以用它创建各种三维场景,包括 ...

最新文章

  1. 二叉树简介及C++实现
  2. CyberRT使用笔记
  3. 技术图文:C# 语言中的扩展方法
  4. app制作流程步骤_企业画册设计流程总结 告诉你画册制作步骤
  5. Linux权限管理总结(1)--基础权限
  6. php 常用的系统函数
  7. 网络编程-网络分层的意义
  8. 片源系统服务器,OUO NAS10主控界面评测
  9. Apache Flink 漫谈系列(06) - 流表对偶(duality)性
  10. Java之观察者模式
  11. CANape编程语言CASL之Script的创建与调用
  12. Java 简单TCP文件传输
  13. DNS中A记录和CNAME的区别 什么是CNAME
  14. 尺度不变特征转换(Scale-invariant feature transform 或 SIFT)
  15. 自定义View中Canvas之Path的详解
  16. try的动词用法_try的用法
  17. 计算最大回撤python_python 计算收益回撤比
  18. 情人节送什么礼物好呢?实用又有纪念意义的礼物推荐
  19. uniapp修改字体
  20. 员工管理系统实现方案

热门文章

  1. 0033:乐队的夏天
  2. MDK470A LIC/ERROR R206: NO REGISTRY ACCESS, ADMINISTRATION RIGHTS REQUIRED
  3. ubuntu安装显卡问题
  4. office受保护视图_使用受保护的视图激发恶意Office文档
  5. JDK和tomcat配置HTTPS协议
  6. mysql存图片二进制文件_将图片(二进制文件)存储于数据库,论文件字节流与二进制字符串相互转换...
  7. python读取docx文件,并进行一些操作
  8. Photoshop - PS/AE渐变工具出现色带波纹色彩过渡不均匀咋办?
  9. wireshark 抓 蓝牙数据_使用Wireshark 抓取数据包
  10. 微信里扫描二维码弹出默认浏览器(苹果打开App Store)打开app的下载链接怎么实现