ok, so, I have a functional component which renders 2 images in a Canvas with some text input from the user. I'm noticing that the 2nd image often doesn't render or say disappears from the Canvas.
I've a small editor which allows user to select fonts, font sizes, text color and font style like Bold and Italics .. these font properties are reflected in the Canvas text.
Below is my code ...
const handleDraw = (
msg,
fontSize,
selectedFont,
textColor,
boldStyle,
italicStyle,
underlineStyle
) => {
const img = document.getElementById("cardImage");
const canvas = canvasRef.current;
const context = canvas.getContext("2d");
var factor = Math.max(canvas.width / img.width, canvas.height / img.height);
const image = new Image();
const logoImage = new Image();
console.log(
"Drawing image....handleDraw was called card content is ",
imageContent
);
image.src = imageContent;
logoImage.src = logo;
canvas.width = image.width + 1200;
canvas.height = image.height + 500;
context.drawImage(image, 0, 0, img.width + 150, img.height - 20);
image.onerror = function(err) {
console.log("card image error : ", err);
};
//below line FAILS to draw an image
context.drawImage(logoImage, img.width + 200, 0, 250, 100);
logoImage.onerror = function(err) {
console.log("Logo Image error ", err);
};
context.font =
(boldStyle ? "bold " : "normal ") +
(italicStyle ? " italic " : " ") +
fontSize +
"px " +
selectedFont;
console.log("context.font ",context.font)
context.fillStyle = textColor;
drawText(context, 400, 40, msg, img.width + 160,
img.height / 6)
};
function drawText(context, maxWidth, lineHeight, text, x, y) {
// Split the text into an array of lines
const lines = text.split("\n");
// Loop through the lines and split into smaller chunks if necessary
const newLines = [];
for (const line of lines) {
let words = line.split(" ");
let currentLine = words[0];
for (let i = 1; i < words.length; i++) {
const width = context.measureText(currentLine + " " + words[i]).width;
if (width > maxWidth) {
newLines.push(currentLine);
currentLine = words[i];
} else {
currentLine += " " + words[i];
}
}
newLines.push(currentLine);
}
// Render the new array of lines on the canvas
for (const line of newLines) {
context.fillText(line, x, y);
y += lineHeight;
}
}