<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebGl 缩放(矩阵变换)</title>
</head>
<body>
<h6>使用键盘方向键↑、↓缩放三角形</h6>
<canvas id="myCanvas" width="500" height="300" style="border: 1px solid red"></canvas>
</body>
<script> window.onload = function () { //第1步 - 准备Canvas和获取WebGL的渲染上下文
var canvas = document.getElementById('myCanvas'),
gl = canvas.getContext('webgl'); //第2步 - 定义几何并将其存储在缓冲区对象
var vertices = [
-0.5,0.5,0.0,
0.0,0.5,0.0,
-0.25,0.25,0.0,
0.5,0.5,0.0,
0.25,0.25,0.0,
],
indices =[0,1,2,1,3,4]; var vertex_buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); var index_buffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); //第3步 - 创建和编译着色器程序
var vertCode =
'attribute vec3 coordinates;' +
'uniform mat4 scale;' +
'void main(void) {' +
' gl_Position = scale*vec4(coordinates,1.0);' +
'}'; var fragCode =
'void main(void) {' +
' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +
'}'; var vertShader = gl.createShader(gl.VERTEX_SHADER);
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(vertShader);
gl.compileShader(fragShader);
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram); //第4步 - 关联着色器程序到缓冲区对象
var coord = gl.getAttribLocation(shaderProgram, 'coordinates');
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(coord); var Sx = 1.5, Sy = 1.5, Sz = 1.5;
var xformMatrix = new Float32Array([
Sx, 0.0, 0.0, 0.0,
0.0, Sy, 0.0, 0.0,
0.0, 0.0, Sz, 0.0,
0.0, 0.0, 0.0, 1.0
]); //然后将矩阵传输给定点着色器
var scale = gl.getUniformLocation(shaderProgram,'scale');
gl.uniformMatrix4fv(scale, false, xformMatrix); //第5步 - 绘制所需的对象
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0, 0, myCanvas.width, myCanvas.height);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0); //监听事件
document.addEventListener("keyup",function (event) {
switch (event.keyCode){
case 38:
Sx += 0.05;
Sy += 0.05;
Sz += 0.05;
break;
case 40:
Sx -= 0.05;
Sy -= 0.05;
Sz -= 0.05;
break;
} //重复以上部分操作
xformMatrix = new Float32Array([
Sx, 0.0, 0.0, 0.0,
0.0, Sy, 0.0, 0.0,
0.0, 0.0, Sz, 0.0,
0.0, 0.0, 0.0, 1.0
]);
gl.uniformMatrix4fv(scale, false, xformMatrix);
//重复 第5步 - 绘制所需的对象
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0, 0, myCanvas.width, myCanvas.height);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0); }); } </script>
</html>