Time for action – creating an HTML5 canvas
Using your favorite editor, create a web page with the following code in it:
<!DOCTYPE html> <html> <head> <title> WebGL Beginner's Guide - Setting up the canvas </title> <style type="text/css"> canvas {border: 2px dotted blue;} </style> </head> <body> <canvas id="canvas-element-id" width="800" height="600"> Your browser does not support HTML5 </canvas> </body> </html>
Note
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Save the file as
ch1_Canvas.html
.Open it with one of the supported browsers.
You should see something similar to the following screenshot:
What just happened?
We have just created a simple web page with a canvas in it. This canvas will contain our 3D application. Let's go very quickly to some relevant elements presented in this example.
Defining a CSS style for the border
This is the piece of code that determines the canvas style:
<style type="text/css"> canvas {border: 2px dotted blue;} </style>
As you can imagine, this code is not fundamental to build a WebGL application. However, a blue-dotted border is a good way to verify where the canvas is located, given that the canvas will be initially empty.
Understanding canvas attributes
There are three attributes in our previous example:
Id: This is the canvas identifier in the Document Object Model (DOM).
Width and height: These two attributes determine the size of our canvas. When these two attributes are missing, Firefox, Chrome, and WebKit will default to using a 300x150 canvas.
What if the canvas is not supported?
If you see the message on your screen: Your browser does not support HTML5 (Which was the message we put between <canvas>
and </canvas>
) then you need to make sure that you are using one of the supported Internet browsers.
If you are using Firefox and you still see the HTML5 not supported message. You might want to be sure that WebGL is enabled (it is by default). To do so, go to Firefox and type about:config
in the address bar, then look for the property webgl.disabled
. If is set to true
, then go ahead and change it. When you restart Firefox and load ch1_Canvas.html
, you should be able to see the dotted border of the canvas, meaning everything is ok.
In the remote case where you still do not see the canvas, it could be due to the fact that Firefox has blacklisted some graphic card drivers. In that case, there is not much you can do other than use a different computer.