Write text on Canvas using React

Today we’ll show you how to write text on canvas using React. In the previous article, we taught you how to draw a line and rectangle on Canvas using ReactJS.

Steps to write text on Canvas

  1. Create a react application
  2. Add the canvas and initialize the context
  3. Function to write a text
  4. Write a text
  5. Output

1. Create a react application

First we have to create a simple react application using create-react-app. Check out the below link for more details.

Create React Application

2. Add the canvas and initialize the context

In the next step, we have to render the canvas element in the DOM and initialize the context of the canvas. Check out the following link for more details.

How to initialize the context of the canvas

3. Function to write a text

Use the following function to write a text on Canvas using react code.

In the above code, we are drawing a text by passing two major parameters such as info and style. We have passed the x and y points via info along with the text param and manage the color, font family, text align and text baseline by passing into the second param. We have used the fillText() method to write a text on canvas.

4. Write a text

Let’s draw a text by using the above method.

5. Output

Combine all code together and see how it looks.

App.js

Run the project and check the output in the browser.

Output - Write text on Canvas using React - Clue Mediator
Output – Write text on Canvas using React – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

1 Response

  1. Szabolcs Szekely says:

    Excellent! Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *