views:

249

answers:

2

Hi all,

Let's say that I got the following code in a page:

elit ac <a href="http://www.ducksanddos/bh.php" id='link'>Hello world!</a> nunc

And that I want to make the <a> contain a <canvas> element which will display the exact same text and will look exactly like the <a> looked before the change, resulting code:

elit ac <a href="http://www.ducksanddos/bh.php" id='link'><canvas width='xxx' height='xxx' /></a> nunc

After investing some time I arrived to this partial solution (btw I also use jQuery):

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   = '';   // delete original content of <a>
element.appendChild(canvas);

}

My problem is that from some reason the text is displayed a little bit higher (few pixels) then the rest of the text which surround the <a> (that's after I gave it an extra 22px at ctx.fillText(content, 0, 22); in order to make the text visible at all..).

When checking with the firebug selector it seems that the <canvas> element is the same size as the <a> but located a little bit higher (which is weird cause it's a child element of it...).

One last thing, all of this code is being run from a Firefox extension so there is no need for compatibility with other browsers.

Thx a lot! Yonatan Ben-Nes

+2  A: 

Keep in mind that a rendered canvas is sort of like an image on the page. So it will follow layout rules as such (this means it may not align exactly with your text on it's own)

You may need to use CSS to align the resulting image element with your text. Try adding the following JS at the end of the above script:

canvas.style.verticalAlign="middle";

That seemed to do it for me when I tried your sample (I provided my own sample html etc). I also had to change the fillText command to:

ctx.fillText("content", 0, 20);

But that could have been because of my browser/OS font settings.

Mike Mytkowski
Thx a lot Mike, it did it wonderfully!
Nimrod Yonatan Ben-Nes
A: 

Could it be that you can just overlay the text on top of the canvas? What exactly do you want the canvas for?

Matchu