Thursday, April 28, 2011

How do you draw text on a <canvas> tag in Safari

I've been experimenting with using the <canvas> tag for drawing simple diagrams and charts, and so far it's pretty easy to work with. I have one issue thought. I can't figure out how to draw text on a <canvas> in Safari. In Firefox 3.0, I can do this:

Chart.prototype.drawTextCentered = function(context, text, x, y, font, color) {
  if (context.mozDrawText) {
    context.save();
    context.fillStyle = color;
    context.mozTextStyle = font;
    x -= 0.5 * context.mozMeasureText(text);
    context.translate(x, y);
    context.mozDrawText(text);
    context.restore();
  }
}

I've seen reference to a fillText() method in Apple's Safari docs, but it doesn't appear to be supported in Safari 3.2. Is this just something that's currently missing, or is it some well-kept secret?

From stackoverflow
  • I don't believe that Safari 3.2 supports rendering text in the canvas.

    According to this blog, Safari 4 beta supports rending text to the canvas, based on the HTML 5 canvas text APIs.

    edit: I have confirmed that the following snippet works in Safari 4 beta:

    <canvas id="canvas"></canvas>
    <script>
        var context = document.getElementById("canvas").getContext("2d");
        context.fillText("Hello, world!", 10, 10);
    </script>
    
    Don McCaughey : Cool, I can live without text 'till Safari 4 is released.
    Neo42 : What about the iPhone as of 12/14/2009? What does it support?
  • This isn't ideal, and it looks like you are fine waiting, but for reference, there's a library called strokeText that does its own font rendering. It works in Firefox 1.5+, Opera 9+, Safari (I don't know what versions) and IE6+ (using VML instead of canvas).

    Don McCaughey : Cool, but I'm using `` for purely internal stuff right now and we all have Firefox installed (and some are using Safari 4 beta).
  • If you really want to use the HTML5 text methods, you should try this library : http://code.google.com/p/canvas-text/

    and the demos are here : http://canvas-text.googlecode.com/svn/trunk/examples/index.html

    It is still in alpha stage, so any bug report and feedback are welcome !:)

  • I have been trying to use the fillText method on a brand new iphone. The text is shown upside down, backwards and way of.

    Does anybody have good experiences using this method on an iphone?

0 comments:

Post a Comment