JSFiddle - React, Tailwind, and code Playground

by durgesh0000

HTML

<canvas id="myCanvas" width="578" height="200"></canvas>

CSS

#myCanvas {
   border: 1px solid #9C9898;
 }

JavaScript

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 = 'blue';
  context.stroke();
}


var canvas = document.getElementById("myCanvas");//get canvas element as js object
var context = canvas.getContext("2d");//get canvas context to play with it

//initialize the variables with the required data
var text = "ScriptStock";
var textAlign = "center";
var textColor = "blue";
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);