Drawing shapes with canvas
The previous lesson introduced canvas: a drawing shift from the SVG paradigm that allows for much better performances.
Now it's time to start coding. Let's draw your first basic shapes with React and Canvas, a deep dive into the world of imperative programming.
🟣 Let's make a circle (again)
In the early modules of this course, you learned how to draw a basic shape like a circle using SVG. As explained in the previous lesson, drawing with canvas is fundamentally different.
We're going to add a single node to our DOM: a canvas element. Then we'll draw content inside it, like on a whiteboard. Let's do it.
1️⃣ Start with a canvas element
Everything begins with the DOM.
In the return statement of our graph component, rather than rendering multiple SVG elements as we did previously, we now render just a single canvas element:
const Graph = () => {
return (
<canvas width={400} height={400}/>
);
}If you inspect your DOM, you'll see the canvas element now! But it's empty for the moment, just a blank whiteboard.
2️⃣ useRef to select it
We've seen this in the axis and Responsiveness modules already.
useRefuseRef is a way to give React a reference to an element, so it can select and manipulate it. We used it to insert axes and to measure the size of a div.
Create a new ref (called canvasRef here) with React's useRef function, then pass it to the canvas element via its ref attribute. In the next step, we'll use canvasRef to draw inside the canvas!
const Graph = () => {
const canvasRef = useRef(null);
return (
<canvas width={400} height={400} ref={canvasRef}/>
);
}3️⃣ useEffect to trigger the drawing
Once more, check the axis lesson where useEffect is described in depth.
Next, we need to "edit" the canvas by drawing on it.
We need to write code that runs after the canvas node is mounted, and that's possible thanks to useEffect.
Notice the getContext() function available on the canvas node. It returns the canvas context: the object we draw into using the canvas syntax.
const Graph = () => {
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current; // find the target canvas element
const ctx = canvas.getContext('2d'); // initialize a canvas "context"
... draw whatever you want in the canvas
}, []);
return (
<canvas width={400} height={400} ref={canvasRef}/>
);
}4️⃣ The canvas syntax
Finally, it's time to create the actual drawing.
For each element, we start by initializing a path with beginPath(). There are various functions available for drawing different shapes. To draw a circle, for example, we use the arc() function.
Oh no! 😱
It seems like you haven't enrolled in the course yet!
This is a lesson from the D3 ❤️ React course, where you learn to create bespoke, interactive graphs with d3.js and React.
Enrollment is currently closed. Join the waitlist to be notified when doors reopen:
Or Login