JSFiddle - React, Tailwind, and code Playground
by Nick Hulea
HTML
<canvas id="myCanvas"></canvas>
<input id="textchange" placeholder="type here !" />
CSS
input {
width:100%;
}
canvas {
width:100%;
}
JavaScript
var textval = document.getElementById('textchange');
var canvas = document.getElementById("myCanvas"); //get canvas element as js object
var context = canvas.getContext("2d"); //get canvas context to play with it
var textUnderline = function (context, text, x, y, color, textSize, align) {
var textWidth = context.measureText(text).width;
var startX = 0;
var startY = y + (parseInt(textSize) / 15);
var endX = 0;
var endY = startY;
var underlineHeight = parseInt(textSize) / 15;
if (underlineHeight < 1) {
underlineHeight = 1;
}
context.beginPath();
if (align == "center") {
startX = x - (textWidth / 2);
endX = x + (textWidth / 2);
} else if (align == "right") {
startX = x - textWidth;
endX = x;
} else {
startX = x;
endX = x + textWidth;
}
context.strokeStyle = color;
context.lineWidth = underlineHeight;
context.moveTo(startX, startY);
context.lineTo(endX, endY);
context.strokeStyle = 'black';
context.stroke();
}
textval.onkeypress = function () {
canvas.width = canvas.width;
//initialize the variables with the required data
var text = textval.value;
var textAlign = "center";
var textColor = "black";
var fontSize = "60pt";
var fontFamily = "Calibri";
//Set the position of the text on canvas
//I am setting it as center of the canvas. You can set as per your need.
var x = canvas.width / 2;
var y = canvas.height / 2;
//Set the canvas context properties
context.font = fontSize + " " + fontFamily;
context.textAlign = textAlign;
context.fillStyle = textColor;
//Display the text on canvas
context.fillText(text, x, y);
//Call the function to underline the text
//We need to pass some values to our function so that it can perform the necessary calculations.
textUnderline(context, text, x, y, textColor, fontSize, textAlign);
console.log(text);
};