How to draw text with line on canvas?

Member

by dedrick , in category: Javascript , 2 months ago

How to draw text with line on canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 2 months ago

@dedrick 

To draw text with a line on a canvas in HTML, CSS, and JavaScript, you can follow these steps:

  1. Create an HTML file with a canvas element:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!DOCTYPE html>
<html>
<head>
  <title>Draw Text with Line on Canvas</title>
</head>
<body>
  <canvas id="myCanvas" width="400" height="200"></canvas>
  <script src="script.js"></script>
</body>
</html>


  1. Create a JavaScript file (script.js) and add the following code to draw text with a line on the canvas:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

ctx.font = '30px Arial';
ctx.fillText('Hello World!', 50, 50);

// Draw a line
ctx.beginPath();
ctx.moveTo(50, 70);
ctx.lineTo(200, 70);
ctx.stroke();


In this code snippet, we first get the canvas element and its context 2D. We then set the font style for the text and use fillText() method to draw the text 'Hello World!' at coordinates (50, 50) on the canvas.


Next, we use beginPath(), moveTo(), lineTo(), and stroke() methods to draw a line from (50, 70) to (200, 70) on the canvas.

  1. Save the files and open the HTML file in a web browser. You should see the text 'Hello World!' and a line drawn on the canvas.


You can customize the font style, text content, text coordinates, line coordinates, and line style (color, width, etc.) as needed.