index previous next

Put data into gpu buffer

  1. Put data into GPU buffer
    1. create buffer
    2. put data into the buffer

We have some data in GPU friendly format, so it's time to upload it to graphics card.

create buffer

Creating buffer is the simplest thing ever. It is just:


var triangleBuffer = gl.createBuffer()

It will create buffer for data on your graphics card. Now you can put items there. Strange thing is, you don't give size of that buffer. I guess it will be allocated during copying.

put data into buffer

Remember how we did with clearing screen with some color? It wasn't


clear(gl.COLOR_BUFFER_BIT, 1.0, 1.0, 0.0, 0.0)

But it was instead


gl.clearColor(1.0, 1.0, 0.0, 1.0)
gl.clear(gl.COLOR_BUFFER_BIT)

Same way is here. You cannot put data directly inside buffer. You can though set a buffer as a current one and put data into current buffer. And this is how you do it.


gl.bindBuffer( gl.ARRAY_BUFFER, triangleBuffer )
gl.bufferData( gl.ARRAY_BUFFER, triangleVertices, gl.STATIC_DRAW )

bindBuffer() sets gl.ARRAY_BUFFER to point to triangleBuffer. So every operation regarding gl.ARRAY_BUFFER will now deal with triangleBuffer. This is just WebGL's way of saying - I want to use this buffer.

bufferData() uploads data into binded buffer. So data from triangleVertices will be uploaded into gl.ARRAY_BUFFER, which points to triangleBuffer. And so our triangle vertices are finally inside graphics card's memory.

The last parameter - STATIC_DRAW - says how that data will be used. In our case it doesn't matter. When you will have to change it, you will know enough to decide for yourself. For the whole tutorial we won't be using any other value in here, so don't worry about it.

Whole code with data upload to graphics card's memory.


<!DOCTYPE html> 

<html>
<head>
<meta charset="UTF-8">
<title>noniwoo webgl tutorial</title>
</head>
<body>
<canvas id="canvas1" width="640" height="480"></canvas>
<script>
var canvas = document.getElementById('canvas1')
if( canvas == null )
{
	throw "Could not get canvas element!"
}

var gl = canvas.getContext('webgl')
if( gl == null )
{
	gl = canvas.getContext('experimental-webgl')
	if( gl == null )
	{
		throw "Could not get webgl context"
	}
}

gl.clearColor(1.0, 1.0, 0.0, 1.0)
gl.clear(gl.COLOR_BUFFER_BIT)

var triangleVertices = new Float32Array([
	 0.0,  1.0,  0.0,  // top
	 1.0, -1.0,  0.0,  // right
	-1.0, -1.0,  0.0   // left
])

var triangleBuffer = gl.createBuffer()
gl.bindBuffer( gl.ARRAY_BUFFER, triangleBuffer )
gl.bufferData( gl.ARRAY_BUFFER, triangleVertices, gl.STATIC_DRAW )

</script>

</body>
</html>

index previous next