@dedrick
To draw text with a line on a canvas in HTML, CSS, and JavaScript, you can follow these steps:
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 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.
You can customize the font style, text content, text coordinates, line coordinates, and line style (color, width, etc.) as needed.