chapter fourteen

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

This chapter is where the mathematical concepts you learned earlier in the book, 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 allow you to control every pixel with precision.

I don't cover the basics of the Canvas API itself but instead focus on some core aspects of its use in modern UI development. In the pages that follow, you learn 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, the process of using the math of coordinates and shapes to determine if a user's click or hover is interacting with something you've drawn.

14.1.1 Drawing a pie chart from data

14.1.2 Creating an interactive bar chart

14.1.3 Advanced hit detection on a donut chart

14.2 Dynamic motion and simulation

14.2.1 Simulating a simple particle system

14.2.2 Creating a generative star field effect

14.2.3 Creating celebration and feedback effects

14.3 Solutions to Exercises

14.4 Summary