Imagine having this snippet of code on a webpage:
elit ac <a href="http://www.ducksanddos/bh.php" id='link'>Hello world!</a> nunc
Now, picture wanting to replace the <a>
tag with a <canvas>
element that displays the same text and looks identical to the original <a>
tag. The resulting code would look like this:
elit ac <a href="http://www.ducksanddos/bh.php" id='link'><canvas width='xxx' height='xxx' /></a> nunc
After some investigation and utilizing jQuery, I came up with this partial solution:
var width = $('#link').width();
var height = $('#link').height();
var element = document.getElementById('link');
var content = element.innerHTML;
var fontfamily = document.defaultView.getComputedStyle(element, null).getPropertyValue('font-family');
var fontsize = document.defaultView.getComputedStyle(element, null).getPropertyValue('font-size');
// create the canvas element
var canvas = doc.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.textBaseline = 'bottom';
ctx.font = fontsize+" "+fontfamily;
ctx.fillText(content, 0, 22);
element.innerHTML = '';
element.appendChild(canvas);
However, my issue is that the text appears a bit higher (few pixels) than the surrounding text after adding an extra 22px at ctx.fillText(content, 0, 22);
to make it visible. Upon inspection with Firebug, the <canvas>
element seems to be the same size as the <a>
, but positioned slightly higher.
Finally, all this code runs within a Firefox extension, so there's no need to worry about browser compatibility.
Thanks for your help! Yonatan Ben-Nes