画布规范没有为我们提供一种测量琴弦高度的方法。但是,您可以设置文本大小(以像素为单位),通常可以找出相对容易的垂直边界。
如果您需要更精确的信息,则可以在画布上放置文本,然后获取像素数据并找出垂直使用了多少像素。这将相对简单,但效率不高。您可以执行以下操作(它可以工作,但是会在您的画布上绘制一些要删除的文本):
function measureTextHeight(ctx, left, top, width, height) {
// Draw the text in the specified area
ctx.save();
ctx.translate(left, top + Math.round(height * 0.8));
ctx.mozDrawText('gM'); // This seems like tall text... Doesn't it?
ctx.restore();
// Get the pixel data from the canvas
var data = ctx.getImageData(left, top, width, height).data,
first = false,
last = false,
r = height,
c = 0;
// Find the last line with a non-white pixel
while(!last && r) {
r--;
for(c = 0; c < width; c++) {
if(data[r * width * 4