webgl实现球体运动效果
代码语言:html
所属分类:动画
代码描述:webgl实现球体运动效果,点击球体可进入球体内部视界
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body, html {
position: absolute;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
background:#000;
cursor: pointer;
}
</style>
</head>
<body translate="no">
<script >
"use strict";
const webgl = {
init() {
this.elem = document.createElement("canvas");
document.body.appendChild(this.elem);
let gl = this.elem.getContext("webgl");
if (!gl) gl = this.elem.getContext("experimental-webgl");
if (!gl) return false;
this.gl = gl;
this.vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(
this.vertexShader,
`
uniform mat4 camProj, camView;
uniform mat4 model;
attribute vec3 position;
uniform vec4 modelColor;
uniform vec3 light1Pos;
uniform vec3 light1Color;
uniform vec3 light2Pos;
uniform vec3 light2Color;
varying vec3 vLightWeighting;
void main(void) {
vec4 normal = model * vec4(position, 0.0);
vec4 worldPosition = model * vec4(position, 1.0);
vec3 lightDirection = normalize(light1Pos - worldPosition.xyz);
float angle = max(dot(lightDirection, (camView * normal).xyz), 0.0);
vLightWeighting = light1Color * angle * modelColor.rgb;
lightDirection = normalize(light2Pos - worldPosition.xyz);
angle = max(dot(lightDirection, normal.xyz), 0.0);
vLightWeighting += light2Color * angle * modelColor.rgb;
gl_Position = camProj * camView * worldPosition;
}
`);
this.fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(
this.fragmentShader,
`
precision highp float;
uniform vec4 modelColor;
varying vec3 vLightWeighting;
void main(void) {
vec3 col = modelColor.rgb * vLightWeighting;
gl_FragColor = vec4(col.rgb, modelColor.a);
}
`);
gl.compileShader(this.vertexShader);
gl.compileShader(this.fragmentShader);
this.program = gl.createProgram();
gl.attachShader(this.program, this.vertexShader);
gl.attachShader(this.program, this.fragmentShader);
gl.linkProgram(this.program);
gl.useProgram(this.program);
this.camera = {
pos: this.vec3(),
mov: this.vec3(),
proj: this.mat4().uniform("camProj"),
view: this.mat4().uniform("camView") };
this.resize();
w.........完整代码请登录后点击上方下载按钮下载查看
















网友评论0