Recently, I have started a quest in order to learn how to work with text on HTML5 canvas. So far I have created the barebones of what will become a realtime text editor.

Right now “Text Arranger” (what I’m calling my app) simply prints to the screen and gives a fill/outline/both option to the user. I’ll be updating it in the coming weeks with more features so it will actually become quite useful.

The JavaScript

All of this is from canvasApp.js, the file where all the application code is stored.

$(document).ready(function() {  
  // Uses Modernizr.js to check for canvas support
  function canvasSupport() {
    return Modernizr.canvas;
  }

  // Once DOM is ready, start the app
  canvasApp();

  function canvasApp() {
    // Check for canvas support
    if (!canvasSupport()) {
      return;
    }

    // Grab the canvas and set the context to 2d
    var theCanvas = $("#canvasOne");
    var context = theCanvas.get(0).getContext("2d");

    // Initialize variables
    var message = "";
    var fillOutline = "fill"; // set default fill/outline to fill

    // Event listeners
    $("#textBox").keyup(textBoxChanged);
    $("#fillOutline").change(fillOutlineChanged);

    // First screen draw
    drawScreen();

    // Event handler functions
    function textBoxChanged(e) {
      var target = e.target;
      message = target.value;
      drawScreen();
    }

    function fillOutlineChanged(e) {
      var target = e.target;
      fillOutline = target.value;
      drawScreen();
    }

    // Draws or updates the screen.
    function drawScreen() {
      // Background
      context.fillStyle = "#ffffff";
      context.fillRect(0, 0, theCanvas.width(), theCanvas.height());

      // Outside Border
      context.strokeStyle = "#000000";
      context.strokeRect(5, 5, theCanvas.width()-10, theCanvas.height()-10);

      // Text
      context.font = "50px serif";

      // Variables created in order to center the text on the canvas
      var metrics = context.measureText(message);
      var textWidth = metrics.width;
      var xPosition = (theCanvas.width()/2) - (textWidth/2);
      var yPosition = (theCanvas.height()/2);

      // Draw the text differently depending on fill or outline (stroke)
      switch(fillOutline) {
        case "fill":
          context.fillStyle = "#000000";
          context.fillText(message, xPosition, yPosition);
          break;
        case "stroke":
          context.strokeStyle = "#000000";
          context.strokeText(message, xPosition, yPosition);
          break;
        case "both":
          context.fillStyle = "#ff0000";
          context.fillText(message, xPosition, yPosition);
          context.strokeStyle = "#000000";
          context.strokeText(message, xPosition, yPosition);
          break;
      }
    }
  }

});

I’ve tried my best to document it as well as I can. The code uses my HTML5 Canvas Skeleton.

You can find the current version of the app here: https://www.zesix.com/html5/textArranger1.0/