# WebGL Simple 2D Example 2

### Make a drawTriangle Function

• A simple code improvement.
• Makes it easier to draw triangles, from wherever we want, and switch their order.

#### Full JavaScript code on this page: (or you can View Page Source)

```var gl, canvas, vertices = []

// UPDATE: Made this handy function.
function drawTriangle(x1, y1, x2, y2, x3, y3) {
vertices.push(x1, y1, x2, y2, x3, y3)
}

function gameLoop() {
window.requestAnimationFrame(gameLoop)

// Clear the screen.
gl.clear(gl.COLOR_BUFFER_BIT)

// UPDATE: Calling my function instead of setting the array.
// Draw the moving triangle.
drawTriangle(
-0.5+Math.sin(Date.now()*.01), 0.5,
-0.5, -0.5,
0.5, -0.5
)
// Another triangle for fun.
drawTriangle(
-0.7, 0.0,
-0.8, -0.2,
-0.6, -0.1
)
// Third triangle for more fun.
drawTriangle(
0.7, 0.0,
0.8, -0.2,
0.6, -0.1
)

// Tell webGL to draw these triangle this frame.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)

// Draw all the triangles.
gl.drawArrays(gl.TRIANGLES, 0, vertices.length/2)

// Clear vertices. We will fill it every frame.
// This way you don't need to delete objects from the screen. You just stop drawing them.
vertices = []
}

function glSetup() {
canvas = document.getElementById("myCanvas")
gl = canvas.getContext("experimental-webgl")

// Set the viewport size to be the whole canvas.
gl.viewport(0, 0, canvas.width, canvas.height)

// Set the background color to sky blue.
gl.clearColor(.5, .7, 1, 1)

// Tell webGL that we aren't doing anything special with the vertex buffer, just use a default one.
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer())

var vertCode =
"attribute vec2 coordinates;" +
"void main(void) {" +
// We are passing in only 2D coordinates. Then Z is always 0.0 and the divisor is always 1.0
" gl_Position = vec4(coordinates, 0.0, 1.0);" +
"}"

// Create a vertex shader object.

var fragCode =
"void main(void) {" +
// We aren't passing in colors right now so all the triangles are green. G=1.0=full green.
" gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);" +
"}"

// Tell webGL to use both my shaders.

// Tell webGL to read 2 floats from the vertex array for each vertex
// and store them in my vec2 shader variable named "coordinates"
`					`