Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
Don McCaughey Avatar asked Apr 05 '09 23:04

Don McCaughey


People also ask

How do you add text to canvas tag?

To draw text on a canvas, the most important property and methods are: font - defines the font properties for the text. fillText(text,x,y) - draws "filled" text on the canvas. strokeText(text,x,y) - draws text on the canvas (no fill)

Does Safari support canvas element?

For best performance, Canvas should be used on the current or first previous major release of Chrome, Firefox, Edge, or Safari. Because it's built using web standards, Canvas runs on Windows, Mac, Linux, iOS, Android, or any other device with a modern web browser.

Which method is used to draw filled text on the canvas?

The fillText() method draws filled text on the canvas. The default color of the text is black. Tip: Use the font property to specify font and font size, and use the fillStyle property to render the text in another color/gradient.

Can you use text on canvas?

Visuals make sense, but using text in canvas prints can be a powerful way to make a statement. Text is a strong design choice, especially used cleverly and combined with affordable, high-quality canvas prints.


2 Answers

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>
like image 76
Brian Campbell Avatar answered Nov 09 '22 07:11

Brian Campbell


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).

like image 25
Matthew Crumley Avatar answered Nov 09 '22 08:11

Matthew Crumley