I have a website where I need to generate dynamic images specific to the user. The approach I found was using canvas. I have text information and image file which need to be copied to the canvas and then, later on, can be converted to the image file which the user can download.
function generateImage() {
let event_date = '11-02-2022'
let event_name = 'Prom Night'
let canvas = document.getElementById("your-canvas")
let ctx = canvas.getContext("2d")
ctx.font = "26px Arial";
ctx.textAlign = 'center'
// For Heading
ctx.fillText(event_date + ' - ' + event_name, 400, 50)
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 100, 100);
}
img.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png'
return canvas.toDataURL('image/jpg')
}
// generateImage()
let image_gen = generateImage()
$('#gen-image').attr('src', image_gen)
CANVAS ELEMENT
IMAGE ELEMENT
![]()
As you can see in the snippet that the image is visible and copied successfully into the canvas but not visible when the canvas is converted into img with toDataURL()