Chapter 6: HTML Graphics (Canvas & SVG)

6.1 Introduction to HTML Graphics

HTML provides two major methods for drawing graphics: Canvas and SVG. Both allow developers to create visual content but have different use cases and implementations.

6.2 The HTML <canvas> Element

The <canvas> element is used to draw graphics on the web page using JavaScript.

Example of Canvas:

    <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
    <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "blue";
        ctx.fillRect(20, 20, 150, 75);
    </script>
        

6.3 The HTML <svg> Element

SVG (Scalable Vector Graphics) is used to create vector-based graphics that are scalable without losing quality.

Example of SVG:

    <svg width="200" height="100">
        <rect width="200" height="100" style="fill:blue;stroke:black;stroke-width:5;" />
    </svg>
        

6.4 Canvas vs. SVG

Feature Canvas SVG
Rendering Raster-based (Pixels) Vector-based (Scalable)
Performance Faster for frequent updates Slower for complex graphics
Interaction Requires JavaScript Built-in event handling

6.5 Summary

In this chapter, we covered: