function basedLineText(canvasStr, ctx, HTMLStr, HTMLContainer, baseline, x, y, font) {
// create our svg elements
var svgNS = 'http://www.w3.org/2000/svg';
var svg = document.createElementNS(svgNS, 'svg');
var txt = document.createElementNS(svgNS, 'text');
var tspan = document.createElementNS(svgNS, 'tspan');
txt.setAttribute('dominant-baseline', baseline);
txt.setAttribute('x', x);
txt.setAttribute('y', y);
tspan.setAttribute('style', 'font:' + font);
txt.appendChild(tspan);
svg.appendChild(txt);
// we will first deal with the canvas part
tspan.textContent = canvasStr;
// we need to append it in the doc to get its BoundingBox
HTMLContainer.appendChild(svg);
// remove the whitespace around our text
var bB = svg.getBBox();
svg.setAttribute('viewBox', bB.x + ',' + bB.y + ',' + bB.width + ',' + bB.height);
svg.setAttribute('width', bB.width);
svg.setAttribute('height', bB.height);
// get the end x position of our text
var left = txt.getBoundingClientRect().right;
// draw it to the canvas
var svgData = new XMLSerializer().serializeToString(svg);
var img = new Image();
img.onload = function() {
ctx.drawImage(this, x, y);
};
img.src = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgData);
// now the HTML side
tspan.textContent = HTMLStr;
// text size probably has changed
var bB = svg.getBBox();
svg.setAttribute('viewBox', bB.x + ',' + bB.y + ',' + bB.width + ',' + bB.height);
svg.setAttribute('width', bB.width);
svg.setAttribute('height', bB.height);
// move our absolutely positioned container
HTMLContainer.style.top = y + 'px';
HTMLContainer.style.left = (x + left) + 'px';
}
var ctx = canvas.getContext('2d');
basedLineText('hello', ctx, ' world', tst1, 'alphabetic', 20, 20, '12px "sans serif"');
basedLineText('hello', ctx, ' world', tst2, 'middle', 20, 60, '32px monospace');
basedLineText('hello', ctx, ' world', tst3, 'hanging', 20, 80, '64px cursive');
div,
canvas {
position: absolute;
top: 0;
left: 0px;
}
/* only html content is affected */
div {
fill: green;
}
<canvas id="canvas" width="200" height="200"></canvas>
<div id="tst1"></div>
<div id="tst2"></div>
<div id="tst3"></div>