The problem I am facing is that the text is entered by a user vertically centered inside the canvas element. I created a test environment to try to solve this problem, which I presented in this post along with the violin. Here is my code:
HTML:
Enter Your Text: <br/>
<textarea id="inputtextuser" onkeyup="inputtextgo()" name="Text">Enter Your</textarea> <br/>
TextBaseline:
<select id="inputtextbaseline" onchange="inputtextgo()";>
<option value="alphabetic">alphabetic</option>
<option value="top">top</option>
<option value="bottom">bottom</option>
<option value="middle">middle</option>
<option value="hanging">hanging</option>
</select> <br/>
<canvas id="canvas1" width="300px" height="200px" >Your browser does not support the HTML5 canvas tag.</canvas> <br/>
<div id ="textheightentered"></div>
CSS
canvas {
border: solid 1px black;
}
JavaScript / jQuery:
var canvas1 = document.getElementById('canvas1');
context1 = canvas1.getContext('2d');
inputtextgo();
function inputtextgo() {
var inputtext = document.getElementById("inputtextuser").value;
var textheight = fontheight(inputtext);
var baseline = document.getElementById("inputtextbaseline").value;
var y = 100 + textheight/2;
context1.clearRect(0, 0, 300, 200);
context1.font = "36px arial";
context1.textBaseline = baseline;
context1.fillText (inputtext, 0, y);
context1.strokeStyle="red";
context1.moveTo(5,100);
context1.lineTo(290,100);
context1.stroke();
$("#textheightentered").text("Text Height: " + textheight);
}
function fontheight(text){
var canvas=document.createElement("canvas");
canvas.width = 1000;
canvas.height = 200;
var ctx=canvas.getContext("2d");
function measureTextHeight(left, top, width, height,text) {
ctx.save();
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.baseline = "top";
ctx.fillText(text, 0, 35);
ctx.restore();
var data = ctx.getImageData(left, top, width, height).data,
first = false,
last = false,
r = height,
c = 0;
while(!last && r) {
r--;
for(c = 0; c < width; c++) {
if(data[r * width * 4 + c * 4 + 3]) {
last = r;
break;
}
}
}
while(r) {
r--;
for(c = 0; c < width; c++) {
if(data[r * width * 4 + c * 4 + 3]) {
first = r;
break;
}
}
if(first != r) return last - first;
}
return 0;
}
ctx.font= "36px arial";
var height = measureTextHeight(0, 0, canvas.width, canvas.height,text);
return height;
}
JSFiddle: http://jsfiddle.net/grapien/R6DWN/3/
, "y", , , . , , y, ( ), , y.
, , canvas. , , - textbaseline. , , . , script, . , .
- - , , .