From e55c8f251dcf0ffc0f01c5b3fffd402f50ac1906 Mon Sep 17 00:00:00 2001 From: Alex Turchyn Date: Sat, 6 Jul 2024 00:52:12 +0300 Subject: [PATCH] automatically lower signature font size if text doesn't fit --- .../submission_form/initials_step.vue | 21 ++++++++++++++++--- .../submission_form/signature_step.vue | 21 ++++++++++++++++--- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/app/javascript/submission_form/initials_step.vue b/app/javascript/submission_form/initials_step.vue index fdb513737..50db77cc0 100644 --- a/app/javascript/submission_form/initials_step.vue +++ b/app/javascript/submission_form/initials_step.vue @@ -251,13 +251,28 @@ export default { const context = canvas.getContext('2d') const fontFamily = 'Arial' - const fontSize = '44px' + const initialFontSize = 50 const fontStyle = 'italic' const fontWeight = '' - context.font = fontStyle + ' ' + fontWeight + ' ' + fontSize + ' ' + fontFamily - context.textAlign = 'center' + const setFontSize = (size) => { + context.font = `${fontStyle} ${fontWeight} ${size}px ${fontFamily}` + } + + const adjustFontSizeToFit = (text, maxWidth, initialSize) => { + let size = initialSize + setFontSize(size) + + while (context.measureText(text).width > maxWidth && size > 1) { + size -= 1 + setFontSize(size) + } + } + + adjustFontSizeToFit(e.target.value, canvas.width / scale, initialFontSize) + + context.textAlign = 'center' context.clearRect(0, 0, canvas.width / scale, canvas.height / scale) context.fillText(e.target.value, canvas.width / 2 / scale, canvas.height / 2 / scale + 11) }, diff --git a/app/javascript/submission_form/signature_step.vue b/app/javascript/submission_form/signature_step.vue index 9bfaf91f4..ccf9eb953 100644 --- a/app/javascript/submission_form/signature_step.vue +++ b/app/javascript/submission_form/signature_step.vue @@ -455,13 +455,28 @@ export default { const context = canvas.getContext('2d') const fontFamily = 'Dancing Script' - const fontSize = '38px' + const initialFontSize = 44 const fontStyle = 'italic' const fontWeight = '' - context.font = fontStyle + ' ' + fontWeight + ' ' + fontSize + ' ' + fontFamily - context.textAlign = 'center' + const setFontSize = (size) => { + context.font = `${fontStyle} ${fontWeight} ${size}px ${fontFamily}` + } + + const adjustFontSizeToFit = (text, maxWidth, initialSize) => { + let size = initialSize + setFontSize(size) + + while (context.measureText(text).width > maxWidth && size > 1) { + size -= 1 + setFontSize(size) + } + } + + adjustFontSizeToFit(e.target.value, canvas.width / scale, initialFontSize) + + context.textAlign = 'center' context.clearRect(0, 0, canvas.width / scale, canvas.height / scale) context.fillText(e.target.value, canvas.width / 2 / scale, canvas.height / 2 / scale + 11) },