
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Draw Text with strokeText in HTML5
The stroketext() method renders the provided text using the current font, linewidth, and strokestyle properties at the specified place.
The path won't be affected by any subsequent fill() or stroke() calls because this method draws directly to the canvas without changing the original route.
Syntax
Following is the syntax for stroke text in HTML
ctx.strokeText(text, x, y, maxWidth);
Where,
X ? The point on the x-axis where the text should start to be drawn, in pixels.
Y ? The baseline's y-axis coordinate, in pixels, at which to start rendering the text.
text ? A string containing the text string that should be rendered in the context.
maxwidth ? The most pixels that the text can have at its widest point. There is no restriction on the text's width if it is not stated.
Let's dive into the following examples to get a clear idea on how to draw a text with stroketext() in HTML5
Example 1
Using the stroketext() function
The canvas is filled with text drawn using the strokeText() method. The text is always displayed in black.
In the following example we are using stroketext() to draw a text with strokes on our canvas.
<!DOCTYPE html> <html> <body> <canvas id="canvas" width="600" height="150"></canvas> <script> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Welcome To The world', 50, 90); </script> </body> </html>
On executing the above script, it will generate the output consisting of the text "welcome to the world" drawn by using stroketext() on the webpage.
Example 2
Restricting the text size
Considering the following example we are using the stroketext() along with max width to get our text drawn up to our required width on our canvas.
<!DOCTYPE html> <html> <body> <canvas id="canvas" width="600" height="150"></canvas> <script> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Welcome To Tutorials', 50, 90,250); </script> </body> </html>
When the script gets executed, it will generate the output consisting of the text "welcome to tutorials" drawn by using stroketext() on the webpage.