JSFiddle - React, Tailwind, and code Playground

by Ghislain999

HTML

<canvas id=myCanvas width=400 height=400></canvas>

JavaScript

// **************************************************
// Functions: subPixelText() and subPixelBitmap()
// **************************************************

var subPixelText = function(ctx,text,x,y,fontHeight){
  var width = ctx.measureText(text).width + 12; // add some extra pixels
  var hOffset = Math.floor(fontHeight);
  var c = document.createElement("canvas");
  c.width  = width * 3; // scaling by 3
  c.height = fontHeight;
  c.ctx    = c.getContext("2d");    
  c.ctx.font = ctx.font;
  c.ctx.globalAlpha = ctx.globalAlpha;
  c.ctx.fillStyle = ctx.fillStyle;
  c.ctx.fontAlign = "left";
  c.ctx.setTransform(3,0,0,1,0,0); // scaling by 3
  c.ctx.imageSmoothingEnabled = false;    
  c.ctx.mozImageSmoothingEnabled = false; // (obsolete)
  c.ctx.webkitImageSmoothingEnabled = false;
  c.ctx.msImageSmoothingEnabled = false;
  c.ctx.oImageSmoothingEnabled = false; 
  // copy existing pixels to new canvas
  c.ctx.drawImage(ctx.canvas,x,y-hOffset,width,fontHeight,0,0,width,fontHeight);
  c.ctx.fillText(text,0,hOffset-3 /* (hardcoded to -3 for letters like 'p', 'g', ..., could be improved) */);    // draw the text 3 time the width
  // convert to sub pixels 
  c.ctx.putImageData(subPixelBitmap(c.ctx.getImageData(0,0,width*3,fontHeight)), 0, 0);
  ctx.drawImage(c,0,0,width-1,fontHeight,x,y-hOffset,width-1,fontHeight);
}  
  
var subPixelBitmap = function(imgData){
  var spR,spG,spB; // sub pixels
  var id,id1; // pixel indexes
  var w = imgData.width;
  var h = imgData.height;
  var d = imgData.data;
  var x,y;
  var ww = w*4;
  var ww4 = ww+4;
  for(y = 0; y < h; y+=1){ // (go through all y pixels)
    for(x = 0; x < w-2; x+=3){ // (go through all groups of 3 x pixels)
      var id = y*ww+x*4; // (4 consecutive values: id->red, id+1->green, id+2->blue, id+3->alpha)
      var output_id = y*ww+Math.floor(x/3)*4;
      spR = Math.round((d[id + 0] + d[id + 4] + d[id + 8])/3);
      spG = Math.round((d[id + 1] + d[id + 5] + d[id + 9])/3);
      spB = Math.round((d[id + 2]...