WebGL - HTML5 Canvas Overview

Hello, future web graphics wizards! Today, we're going to embark on an exciting journey into the world of WebGL and HTML5 Canvas. As your friendly neighborhood computer teacher, I'm thrilled to guide you through this adventure. Don't worry if you're new to programming – we'll start from the very basics and work our way up. So, grab your virtual paintbrush, and let's get started!

WebGL - Html5 Canvas Overview

HTML5 Canvas

What is HTML5 Canvas?

Imagine you have a magical digital canvas where you can draw anything you want using code. That's essentially what HTML5 Canvas is! It's a powerful element introduced in HTML5 that allows us to draw graphics, create animations, and even build games right in our web browsers.

Creating Your First Canvas

Let's start by creating a simple HTML5 Canvas:

<!DOCTYPE html>
<html>
<head>
    <title>My First Canvas</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
</body>
</html>

In this example, we've created a canvas element with an id of "myCanvas", a width of 400 pixels, and a height of 200 pixels. It's like setting up an easel with a blank canvas – now we're ready to paint!

Drawing on the Canvas

Now that we have our canvas, let's draw something on it. We'll use JavaScript to do this:

<!DOCTYPE html>
<html>
<head>
    <title>Drawing on Canvas</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        ctx.fillStyle = 'blue';
        ctx.fillRect(10, 10, 100, 50);
    </script>
</body>
</html>

Let's break this down:

  1. We get a reference to our canvas element using getElementById.
  2. We obtain the 2D rendering context of the canvas using getContext('2d').
  3. We set the fill color to blue using fillStyle.
  4. Finally, we draw a blue rectangle using fillRect(x, y, width, height).

When you open this in your browser, you'll see a blue rectangle appear on your canvas. Congratulations! You've just created your first digital painting!

The Rendering Context

What is a Rendering Context?

Think of the rendering context as your set of painting tools. It provides the methods and properties that allow you to draw on the canvas. In the previous example, we used the 2D rendering context, but there are other types as well.

2D Rendering Context

The 2D rendering context is the most commonly used and provides a wide range of 2D drawing functions. Here's a table of some useful 2D context methods:

Method Description
fillRect(x, y, width, height) Draws a filled rectangle
strokeRect(x, y, width, height) Draws the outline of a rectangle
fillText(text, x, y) Draws filled text on the canvas
strokeText(text, x, y) Draws the outline of text on the canvas
beginPath() Starts a new path
moveTo(x, y) Moves the path to the specified point
lineTo(x, y) Draws a line to the specified point
arc(x, y, radius, startAngle, endAngle) Draws an arc or circle

Let's use some of these methods to create a more complex drawing:

<!DOCTYPE html>
<html>
<head>
    <title>Complex Drawing</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // Draw a house
        ctx.fillStyle = 'brown';
        ctx.fillRect(100, 100, 150, 100);

        // Draw a roof
        ctx.fillStyle = 'red';
        ctx.beginPath();
        ctx.moveTo(100, 100);
        ctx.lineTo(175, 50);
        ctx.lineTo(250, 100);
        ctx.fill();

        // Draw a door
        ctx.fillStyle = 'yellow';
        ctx.fillRect(160, 150, 30, 50);

        // Draw text
        ctx.fillStyle = 'black';
        ctx.font = '20px Arial';
        ctx.fillText('My House', 140, 190);
    </script>
</body>
</html>

In this example, we've drawn a simple house using various 2D context methods. We used fillRect for the house body and door, beginPath, moveTo, and lineTo for the roof, and fillText to add a label. Play around with the coordinates and colors to create your own unique house!

WebGL Context

Introduction to WebGL

Now, let's step into the exciting world of 3D graphics with WebGL. WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins.

Getting the WebGL Context

To use WebGL, we need to get the WebGL rendering context instead of the 2D context. Here's how:

<!DOCTYPE html>
<html>
<head>
    <title>WebGL Context</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="300"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var gl = canvas.getContext('webgl');

        if (!gl) {
            console.log('WebGL not supported, falling back on experimental-webgl');
            gl = canvas.getContext('experimental-webgl');
        }

        if (!gl) {
            alert('Your browser does not support WebGL');
        }
    </script>
</body>
</html>

In this example, we try to get the WebGL context. If it's not supported, we fall back to the experimental-webgl context. If that's not available either, we alert the user that their browser doesn't support WebGL.

A Simple WebGL Example

Let's create a simple WebGL example that clears the canvas with a color:

<!DOCTYPE html>
<html>
<head>
    <title>Simple WebGL</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="300"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var gl = canvas.getContext('webgl');

        if (!gl) {
            console.log('WebGL not supported, falling back on experimental-webgl');
            gl = canvas.getContext('experimental-webgl');
        }

        if (!gl) {
            alert('Your browser does not support WebGL');
        } else {
            // Set clear color to red, fully opaque
            gl.clearColor(1.0, 0.0, 0.0, 1.0);
            // Clear the color buffer with specified clear color
            gl.clear(gl.COLOR_BUFFER_BIT);
        }
    </script>
</body>
</html>

In this example, we set the clear color to red using gl.clearColor(red, green, blue, alpha), where each value ranges from 0.0 to 1.0. Then we clear the color buffer with this color using gl.clear(gl.COLOR_BUFFER_BIT). When you run this, you should see a red canvas.

Remember, WebGL is much more complex than 2D canvas rendering and involves concepts like shaders, buffers, and matrices. But don't worry! We'll explore these in future lessons.

Conclusion

Congratulations! You've taken your first steps into the world of HTML5 Canvas and WebGL. We've covered the basics of creating a canvas, drawing in 2D, and even dipped our toes into the 3D world of WebGL.

Remember, learning graphics programming is like learning to paint – it takes practice and patience. Don't be afraid to experiment with the code examples, change values, and see what happens. The more you play around, the better you'll understand how everything works.

In our next lesson, we'll dive deeper into more advanced 2D canvas techniques and start exploring the fascinating world of WebGL shaders. Until then, keep coding and happy drawing!

Credits: Image by storyset