Q. I possess both an image and a string, for example, 'Test' and image is 'sample.jpg'. Provide a JAVASCRIPT code that combines the string 'Test' with the image 'sample.jpg', merging them into a single image 'output.jpg'.
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Merge Text and Image</title>
</head>
<body>
<script>
function mergeTextAndImage(text, imagePath) {
// Create an HTML image element
var img = new Image();
// When the image is loaded, perform the merging
img.onload = function() {
// Create a canvas element
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
// Set canvas dimensions to match the image
canvas.width = img.width;
canvas.height = img.height;
// Draw the image on the canvas
context.drawImage(img, -10,-50);
// Set the text properties
context.font = '40px Arial'; // You can change the font and size here
context.fillStyle = 'white'; // Text color
// Set the position to place the text on the canvas
var x = 10; // X-coordinate
var y = 30; // Y-coordinate
// Draw the text on the canvas
context.fillText(text, x, y);
// Create a new image with the merged content
var mergedImage = new Image();
mergedImage.src = canvas.toDataURL('image/png');
// Append the merged image to the body or display it as needed
document.body.appendChild(mergedImage);
};
// Set the source of the image
img.src = imagePath;
}
// Example usage
var text = 'Test';
var imagePath = 'path/to/sample.jpg'; // Change this to the path of your image
mergeTextAndImage(text, imagePath);
</script>
</body>
</html>
No comments:
Post a Comment