目录
//DrawRectangle.js
function(){
//获取<canvas>元素
var canvas = document.getElementById(‘example‘);//example是在html文件中定义的canvas元素的id;
if(!canvas){
console.log(‘Failed to review the <canvas> element‘);
return;
}
//获取绘制二维图形的绘图上下文
var ctx = canvas.getContext(‘2d‘);
//绘制蓝色矩形
ctx.fillSyle = ‘rgba(0,0,255,1.0)‘;//设置填充颜色为蓝色,r:红;g:绿;b:蓝;a:透明度;
ctx.fillRect(120,10,150,150);//使用填充颜色填充矩形
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Clear canvas</title>
</head>
<body onload="main()">
<canvas id="webgl" width="400" height="400">
Please use the browser supporting "canvas"
</canvas>
<script src="../lib/webgl-utils.js"></script>
<script src="../lib/webgl-debug.js"></script>
<script src="../lib/cuon-utils.js"></script>
<script src="HelloCanvas.js"></script>
</body>
</html>
其中onload="main()"表示在body执行结束之后执行main()函数,而main()函数在HelloCanvas文件中,因此这也是进入HelloCanvas文件的入口;
和之前的以RGB的形式指定WebGL的背景色不一样,这里不能直接使用先指定绘图颜色再绘制的方式。WebGL依赖于一种新的方式成为着色器的绘图机制。
var VSHADER_SOURCE=
‘void main() {\n‘ +
‘gl_Position = vec4(0.0,0.0,0.0,1.0);\n‘ +//设置坐标
‘gl_PointSize = 10.0;\n‘ +//设置尺寸
‘}\n‘;
var FSHADER_SOURCE=
‘void main() {\n‘ +
‘gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n‘ +//设置颜色
‘}\n‘;
在代码中,着色器程序是以字符串的形式“嵌入”在javascript文件中,在程序真正开始运行前它就已经设置好了。
重要: WebGL程序包括运行在浏览器中的JavaScript和运行在WebGL系统的着色器程序这两个部分。
使用attribute变量:传输的是那些与顶点相关的数据
使用uniform变量:传输的是那些对于所有顶点都相同的数据
在顶点着色器中,声明attribute变量;
var VSHADER_SOURCE= ‘attribute vec4 a_Position;\n‘ + ‘void main() {\n‘ + ‘gl_Position = a_Position;\n‘ +//设置坐标 ‘gl_PointSize = 10.0;\n‘ +//设置尺寸 ‘}\n‘;
attribute:存储限定符;
vec4:类型(数组)
a_Position:变量名
将attribute变量赋值给gl_Position变量;
//获取attribute变量的存储位置
var a_Position = gl.getAttributeLocation(gl.program,‘a_Position‘);
if(a_Position < 0) {
console.log(‘Failed to get the storage location of a_Position‘);
return;
}
gl.program:程序对象(包括顶点着色器好片元着色器)
a_Position:想要获取处处地址的attribute变量的名称
向attribute变量传输数据;
//将顶点位置传输给attribute变量
gl.vertexAttrib3f(a_Position,0.0,0.0,0.0);
a_Position:attribute变量的存储地址
后三个参数:x、y、z坐标值
省略了w透明度分量,函数会默认将第四个分量设置为1.0。
改变点的颜色可以使用uniform变量实现
在片元着色器中准备uniform变量;
var FSHADER_SOURCE= ‘precision mediump float;\n‘ + ‘uniform vec4 u_FragColor;\n‘ +//uniform变量 ‘void main() {\n‘ + ‘gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n‘ +//设置颜色 ‘}\n‘;
//获取attribute变量的存储位置 var u_FragColor = gl.getUniformLocation(gl.program,‘u_FragColor‘); if(u_FragColor < 0) { console.log(‘Failed to get the storage location of u_FragColor‘); return; }
将颜色数据从javascript传给uniform变量;
gl.uniform4f(u_FragColor,rgba[0],rgba[1],rgba[2],rgba[3]);
//注册鼠标点击事件响应函数
canvas.onmousedown = function(ev) { click(ev,gl,canvas,a_Position); };
将坐标从浏览器客户区坐标系下转换到canvas坐标系下
var x = ev.clientX; var y = ev.clientY; var rect = ev.target.getBoundingClientRect();
将坐标从canvas坐标系下转换到WebGL下
x = ((x - rect.left) - canvas.width/2)/(canvas.width/2);//<canvas>的中心点坐标是(canvas.height/2, canvas.width/2);
y = (canvas.height/2 - (y - rect.top))/(canvas.height/2);
原文:https://www.cnblogs.com/heihuifei/p/9929054.html