HTML5 Canvas Text Experiments

Find out how big the characters are and how to use that information to locate them in detail.

by Robert Churchill

HTML

<canvas id="canvas2" height="220px" width="480px">The HTML5 Canvas object is not supported on your browser.</canvas>

JavaScript

var canvas2 = document.getElementById("canvas2");
    var ctx2 = canvas2.getContext("2d");
    ctx2.lineWidth = 1.0;
    ctx2.lineCap = "square";  //"round"  "butt" (default)
    canvas2.style.border = "1px solid blue";

    ctx2.beginPath();
    var width2 = canvas2.width;
    var height2 = canvas2.height;
    ctx2.fillStyle = "#FFFFFF";
    ctx2.fillRect(0,0,width2,height2);
    ctx2.strokeStyle = "#000000";  //red for test line
    
    var o_x = 25.0; var o_y = 25.0;
    var s_x = 9.0;  var s_y = 9.0;
    var r_x = 10.0; var r_y = 10.0;
    function pixel(x,y,color) {
      ctx2.strokeStyle = color;
      ctx2.fillStyle = color;
      ctx2.beginPath();
      ctx2.rect(o_x+(x*r_x)+1,o_y+(y*r_y)+1,s_x,s_y);
      ctx2.fill();
    }
    
    function drawYLabel(y,y_label) {
      ctx2.font = "12px Arial";
      ctx2.fillStyle = "#000000";
      ctx2.textAlign = "right";
      ctx2.fillText(y_label,(o_x-3),(o_y+((y+1)*r_y)));
    }
    function drawXLabel(x,x_label) {
      ctx2.font = "12px Arial";
      ctx2.fillStyle = "#000000";
      ctx2.textAlign = "center";
      ctx2.fillText(x_label,o_x+(x*r_y)+Math.floor(r_y*0.5),o_y-3);
    }
    
    //draw grid
    var gi = 0; var gj = 0;
    for (gi=25; gi<200; gi+=10) {
      ctx2.moveTo(25.5,gi+0.5);
      ctx2.lineTo(195.5,gi+0.5);
      ctx2.stroke();
      ctx2.moveTo(gi+0.5,25.5);
      ctx2.lineTo(gi+0.5,195.5);
      ctx2.stroke();
    }
    //draw labels
    drawYLabel(13,"0");
    drawYLabel(11,"-2");
    drawYLabel(9,"-4");
    drawYLabel(7,"-6");
    drawYLabel(5,"-8");
    drawYLabel(3,"-10");
    drawYLabel(1,"-12");
    drawYLabel(15,"2");
    drawYLabel(17,"4");
    
    drawXLabel(0,"0");
    drawXLabel(2,"2");
    drawXLabel(4,"4");
    drawXLabel(6,"6");
    drawXLabel(10,"0");
    drawXLabel(12,"2");
    drawXLabel(14,"4");
    drawXLabel(16,"6");
    
    //draw number 8
    pixel(2,4,"#666666");
    pixel(3,4,"#666666");
    pixel(4,4,"#666666");
    pixel(2,8,"#666666");
   ...