JSFiddle - React, Tailwind, and code Playground

by icodeforlove

HTML

<!-- 
nothing matches perfectly out of the box

but you can exactly match a canvas by centering the baseline and manually centering the text in the DOM based on its bounding box

- SVG
- CANVAS
- HTML
-->

CSS

body {
    margin: 0;
}

JavaScript

var word = {"word":"shit","orientation":"h","fontSize":"269","fontFamily":"Arial","x":80,"y":137.5,"w":480,"h":313};

var canvas = document.createElement('canvas'),
    context = canvas.getContext('2d');

document.body.appendChild(canvas);

canvas.style.cssText = 'position: absolute; left: 0; top: 0; -webkit-transform-origin: 0 0; -webkit-transform: scale(.5); -moz-transform-origin: 0 0; -moz-transform: scale(.5)';
canvas.width = word.w * 2;
canvas.height = word.h * 2;

context.textBaseline = 'middle';
context.font = (word.fontSize*2) + 'px ' + word.fontFamily;
context.fillText(word.word, word.x*2, word.y*2);

var textContainer = document.createElement('span');
textContainer.style.cssText = 'position: absolute; left: ' + word.x + 'px; top: ' + word.y + 'px; color: red; font: ' + word.fontSize + 'px ' + word.fontFamily + '; opacity: .7; height: ' + word.h + '; width: ' + word.w + 'px; border: 1px solid red; ' ;
textContainer.innerHTML = word.word;

document.body.appendChild(textContainer);
var rect = textContainer.getBoundingClientRect();
textContainer.style.top = (word.y - textContainer.offsetHeight/2) + 'px';
//alert(textContainer.offsetHeight)
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', word.w);
svg.setAttribute('height', word.h);
svg.setAttribute('style', 'border: 1px solid red; position: absolute; left: 0; top: 0; font-family: ' + word.fontFamily + '; font-size: ' + word.fontSize + 'px; opacity: .5');

var svgNS = svg.namespaceURI;

var rect = document.createElementNS(svgNS,'text');
rect.setAttribute('text-anchor', 'middle');
rect.setAttribute('fill', 'currentColor');
rect.setAttribute('x', '50%');
rect.setAttribute('y', '50%');
rect.setAttribute('dy', '.3em');
rect.appendChild(document.createTextNode(word.word));
svg.appendChild(rect);
document.body.appendChild(svg);