@denis
To add text on an image using JavaScript and Canvas, you can follow these steps:
- Create an HTML
1
|
<canvas id="myCanvas"></canvas>
|
- Get the reference to the canvas using JavaScript:
1
2
|
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
|
- Load the image using JavaScript:
1
2
|
var image = new Image();
image.src = "path/to/image.jpg";
|
- Once the image is loaded, draw it on the canvas:
1
2
3
|
image.onload = function() {
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
};
|
- Set the font and text properties:
1
2
3
|
ctx.font = "30px Arial";
ctx.fillStyle = "white";
ctx.textAlign = "center";
|
- Use the fillText() method to add the text on the canvas:
1
|
ctx.fillText("Sample Text", canvas.width/2, canvas.height/2);
|
Here, "Sample Text"
is the text you want to display.
- Optionally, you can customize the position, style, and properties of the added text, based on your requirements.
- To save the canvas as an image, you can convert it to a data URL using the toDataURL() method:
1
|
var dataURL = canvas.toDataURL(); // returns base64-encoded image data
|
You can then use this dataURL
to display or save the image.
By following these steps, you can add text on an image using JavaScript and the HTML5 Canvas element.