14 Canvas-based math and drawing
This chapter covers
- Creating canvas-based data visualizations
- Detecting hits on data elements
- Creating canvas-based particle systems
- Simulating a balloon drop, a star field, and a confetti shower
In this chapter, all the mathematical concepts you learned earlier, from geometry and trigonometry to physics and animation, come together in a uniquely creative space: the HTML canvas element. Unlike DOM elements, which have structure and style, a canvas is a blank slate, a grid of pixels waiting for instructions. Your primary tools for creating on this slate are JavaScript and the mathematical principles that let you control every pixel with precision.
This chapter does not cover the basics of the Canvas API itself, but it focuses instead on some core aspects of its use in modern UI development. In the pages that follow, you will learn how to translate abstract data into visual geometry, detect hits on visual elements, and create dynamic motion with physics simulations.
14.1 Data-driven geometry and hit detection
HTML elements provide a built-in structure for content. On a canvas, you must create this structure yourself using math. This is especially true when visualizing data, where you need to map numbers to geometric shapes. The reverse is just as important. Hit detection is the process of using the math of coordinates and shapes to determine whether a user’s click or hover is interacting with something you’ve drawn.