Design Converter
Education
Developer Advocate
Last updated on Oct 24, 2023
Last updated on Oct 12, 2023
In the world of web development, React has become a popular JavaScript library due to its declarative and reactive bindings. It allows developers to create complex user interfaces with ease. One of the features that make React stand out is its ability to work with the HTML5 canvas element. This blog will explore how to draw on a canvas in a React app using the React canvas draw plugin.
The canvas element is a powerful tool that allows developers to draw graphics on a web page. With React, we can create a canvas component that can be reused and controlled through React's state and props. This approach offers a very performant way to draw complex graphics, as the canvas operations are executed directly on the GPU.
Before we start drawing on the canvas, we need to set up our React native environment. First, we need to create a new React project. You can do this by running the following command in your terminal:
1npx create-react-app react-canvas-draw 2
After the project is created, navigate into the project directory and start the project using npm start.
The first step in creating a canvas component in React is to define the component. We will create a functional component named Canvas. Inside this function, we will return a canvas element. We will use the useRef hook to create a canvas ref, which will allow us to access the canvas element directly. This is necessary because we need to access the context of the canvas to draw on it.
1import React, { useRef } from 'react'; 2 3function Canvas() { 4 const canvasRef = useRef(null); 5 6 return ( 7 <canvas ref={canvasRef} /> 8 ); 9} 10 11export default Canvas; 12
In the above code, we have created a canvas component and a canvas ref. We have attached the ref to the canvas element using the ref prop. This will allow us to access the canvas element directly using the canvasRef.current property.
Now that we have our canvas component, we can start drawing on it. To do this, we will use the useEffect hook to run a side effect after the component mounts. Inside the useEffect hook, we will get the context of the canvas and start drawing.
1import React, { useRef, useEffect } from 'react'; 2 3function Canvas() { 4 const canvasRef = useRef(null); 5 6 useEffect(() => { 7 const canvas = canvasRef.current; 8 const context = canvas.getContext('2d'); 9 10 // Start drawing 11 context.fillStyle = 'blue'; 12 context.fillRect(50, 50, 100, 100); 13 }, []); 14 15 return ( 16 <canvas ref={canvasRef} /> 17 ); 18} 19 20export default Canvas; 21
In the above code, we first get the canvas and its context. We then set the fill style to blue and draw a rectangle on the canvas. The rectangle will be filled with the color blue.
The canvas ref in React is used to get a reference to the canvas element. This is necessary because we need to interact with the canvas element directly to draw graphics. The useRef hook is used to create the ref, and the ref is then attached to the canvas element using the ref prop.
The canvas ref gives us access to the canvas element and its properties and methods. For example, we can use the canvas ref to get the context of the canvas, which is necessary to draw on the canvas.
Drawing complex canvas graphics with React involves using the context of the canvas to draw shapes and paths. For example, you can draw a circle on the canvas like this:
1import React, { useRef, useEffect } from 'react'; 2 3function Canvas() { 4 const canvasRef = useRef(null); 5 6 useEffect(() => { 7 const canvas = canvasRef.current; 8 const context = canvas.getContext('2d'); 9 10 // Start drawing 11 context.beginPath(); 12 context.arc(100, 100, 50, 0, 2 * Math.PI); 13 context.fillStyle = 'red'; 14 context.fill(); 15 }, []); 16 17 return ( 18 <canvas ref={canvasRef} /> 19 ); 20} 21 22export default Canvas; 23
In the above code, we first begin a new path and then create an arc, which is a part of a circle. We then fill the arc with the color red. This will draw a red circle on the canvas.
React allows us to add event listeners to the canvas element, enabling user interactions. For instance, we can draw on the canvas where the user clicks or drags the mouse. Here's an example:
1import React, { useRef, useEffect } from 'react'; 2 3function Canvas() { 4 const canvasRef = useRef(null); 5 6 useEffect(() => { 7 const canvas = canvasRef.current; 8 const context = canvas.getContext('2d'); 9 10 // Function to draw a circle where the user clicks 11 const draw = (event) => { 12 const rect = canvas.getBoundingClientRect(); 13 const x = event.clientX - rect.left; 14 const y = event.clientY - rect.top; 15 16 context.beginPath(); 17 context.arc(x, y, 10, 0, 2 * Math.PI); 18 context.fillStyle = 'green'; 19 context.fill(); 20 }; 21 22 // Add the event listener 23 canvas.addEventListener('mousedown', draw); 24 25 // Clean up function 26 return () => { 27 canvas.removeEventListener('mousedown', draw); 28 }; 29 }, []); 30 31 return ( 32 <canvas ref={canvasRef} /> 33 ); 34} 35 36export default Canvas; 37
In the above code, we define a draw function that draws a circle at the position of the mouse click. We then add an event listener for the mousedown event to the canvas. When the user clicks on the canvas, the draw function is called.
One of the advantages of using a canvas is that you can easily save and export the drawings. The canvas provides a method called toDataURL, which returns a data URL representing the image in the canvas. This data URL can be used to display the image or save it to a file.
Here's an example of how to create a button that saves the canvas drawing as an image:
1import React, { useRef, useEffect } from 'react'; 2 3function Canvas() { 4 const canvasRef = useRef(null); 5 6 const saveImage = () => { 7 const canvas = canvasRef.current; 8 const dataUrl = canvas.toDataURL('image/png'); 9 10 const link = document.createElement('a'); 11 link.href = dataUrl; 12 link.download = 'canvas.png'; 13 link.click(); 14 }; 15 16 return ( 17 <div> 18 <canvas ref={canvasRef} /> 19 <button onClick={saveImage}>Save Image</button> 20 </div> 21 ); 22} 23 24export default Canvas; 25
In the above code, we create a saveImage function that gets the data URL of the canvas and creates a download link. When the user clicks the Save Image button, the saveImage function is called, and the canvas image is downloaded.
While React Canvas allows you to draw DOM-like objects on a canvas, the Konva framework takes it a step further. Konva is a well-known declarative 2D drawing library for the web. It provides a React plugin, react-konva, that allows you to draw on a canvas using React components.
React-konva and React Canvas have a similar data flow model and use a similar declarative markup. However, react-konva offers more features out of the box, such as event handling for shapes, layering, and complex shape morphing. It also provides a more extensive set of primitives like lines, circles, and polygons.
Here's an example of how to draw a circle using react-konva:
1import React from 'react'; 2import { Stage, Layer, Circle } from 'react-konva'; 3 4function Canvas() { 5 return ( 6 <Stage width={window.innerWidth} height={window.innerHeight}> 7 <Layer> 8 <Circle x={100} y={100} radius={50} fill='red' draggable /> 9 </Layer> 10 </Stage> 11 ); 12} 13 14export default Canvas; 15
In the above code, we create a Stage (which is equivalent to the canvas), add a Layer (which can contain multiple shapes), and then add a Circle to the Layer. The Circle component has props for x and y coordinates, radius, fill color, and whether it's draggable.
React Canvas Draw provides a powerful way to create interactive graphics in a React application. By combining the flexibility of the canvas element with the power of React's declarative and reactive bindings, developers can create complex and interactive graphics with ease.
Whether you're creating a simple drawing application or a complex game, React Canvas Draw offers a performant and flexible solution. And with the ability to save and export drawings, the possibilities are endless.
Remember, while this blog focused on drawing shapes, the canvas element can do much more. You can draw images, create animations, and even apply image filters. So, start experimenting and see what you can create with React Canvas Draw!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.