in client/src/services/image-rendering.ts [77:111]
async renderImage(imageData: Blob, word: WordTranslation, sourceLanguage: Language,
endangeredLanguage: EndangeredLanguage, width: number, height: number): Promise<Blob> {
const imageURL = URL.createObjectURL(imageData);
let image: HTMLImageElement;
try {
image = await ImageRenderingService._loadImage(imageURL);
} catch(ex) {
URL.revokeObjectURL(imageURL);
throw ex;
}
const canvas: HTMLCanvasElement = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const imageWidth = image.naturalWidth;
const imageHeight = image.naturalHeight;
const context = canvas.getContext('2d');
if (!context) {
throw new Error('Unable to create canvas context');
}
// multiplier to scale canvas down to contain image dimensions
const imageScale = Math.min(imageWidth / width, imageHeight / height);
const croppedImageWidth = Math.round(width * imageScale);
const croppedImageHeight = Math.round(height * imageScale);
const croppedImageDx = (imageWidth - croppedImageWidth) * 0.5;
const croppedImageDy = (imageHeight - croppedImageHeight) * 0.5;
context.drawImage(image, croppedImageDx, croppedImageDy, croppedImageWidth, croppedImageHeight, 0, 0, width, height);
const scale = Math.min(width / window.innerWidth, height / window.innerHeight);
await this._renderBanner(context, width, scale);
if (!word) {
return canvasToBlob(canvas);
}
context.setTransform(scale, 0, 0, scale, 0, 0);
this._renderTranslations(context, word, sourceLanguage, endangeredLanguage, width, height, scale);
return canvasToBlob(canvas);
}