So far, we have rendered very simple objects. Now let's study a way to load the geometry (vertices and indices) from a file instead of declaring the vertices and the indices every time we call initBuffers
. To achieve this, we will make asynchronous calls to the web server using AJAX. We will retrieve the file with our geometry from the web server and then we will use the built-in JSON parser to convert the context of our files into JavaScript objects. In our case, these objects will be the vertices
and indices
array.
JSON stands for JavaScript Object Notation. It is a lightweight, text-based, open format used for data interchange. JSON is commonly used as an alternative to XML.
The JSON format is language-agnostic. This means that there are parsers in many languages to read and interpret JSON objects. Also, JSON is a subset of the object literal notation of JavaScript. Therefore, we can define JavaScript objects using JSON.
Let's see how this work. Assume for example that we have the model
object with two arrays vertices
and indices
(does this ring any bells?). Say that these arrays contain the information described in the cone example (ch2_Cone.html
) as follows:
vertices =[1.5, 0, 0, -1.5, 1, 0, -1.5, 0.809017, 0.587785, -1.5, 0.309017, 0.951057, -1.5, -0.309017, 0.951057, -1.5, -0.809017, 0.587785, -1.5, -1, 0, -1.5, -0.809017, -0.587785, -1.5, -0.309017, -0.951057, -1.5, 0.309017, -0.951057, -1.5, 0.809017, -0.587785]; indices = [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 6, 0, 6, 7, 0, 7, 8, 0, 8, 9, 0, 9, 10, 0, 10, 1];
Following the JSON notation, we would represent these two arrays as an object, as follows:
var model = { "vertices" : [1.5, 0, 0, -1.5, 1, 0, -1.5, 0.809017, 0.587785, -1.5, 0.309017, 0.951057, -1.5, -0.309017, 0.951057, -1.5, -0.809017, 0.587785, -1.5, -1, 0, -1.5, -0.809017, -0.587785, -1.5, -0.309017, -0.951057, -1.5, 0.309017, -0.951057, -1.5, 0.809017, -0.587785], "indices" : [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 6, 0, 6, 7, 0, 7, 8, 0, 8, 9, 0, 9, 10, 0, 10, 1]};
From the previous example, we can infer the following syntax rules:
Array
are defined in the same way you would define them in JavaScriptMost modern web browsers support native JSON encoding and decoding through the built-in JavaScript object JSON
. Let's examine the methods available inside this object:
Method |
Description |
---|---|
|
We use |
|
We use |
Let's learn how to encode and decode with the JSON notation.
3.147.238.70