Text

In this chapter you will learn:

  1. How to draw text on canvas

Draw text

Drawing Text

We can draw text on the canvas.

NameDescriptionReturns
fillText(text, x, y, width)fills the text at the position (x, y). The optional width argument sets an upper limit on the widthvoid
strokeText(text, x, y, width)strokes the text at the position (x, y). The optional width argument sets an upper limit on the widthvoid

There are three drawing state associated with text drawing:

NameDescriptionReturns
fontSets the font used when text is drawnstring
textAlignSets the alignment of the text: start, end, left, right, centerstring
textBaselineSets the text baseline: top, hanging, middle, alphabetic, ideographic, bottomstring

The following code shows how to draw string text on a canvas.

<!DOCTYPE HTML><!--from   ja v a 2  s. c  om-->
<html>
<head>
<style>
canvas {
      border: thin solid black
}

body>* {
      float: left;
}
</style>
</head>
<body>
      <canvas id="canvas" width="850" height="840"> 
      Your browser doesn't support the <code>canvas</code> element 
      </canvas>
      <script>
            var ctx = document.getElementById("canvas").getContext("2d");
            ctx.fillStyle = "lightgrey";
            ctx.strokeStyle = "black";
            ctx.lineWidth = 3;
            ctx.font = "100px sans-serif";
            ctx.fillText("java2s.com", 50, 100);
            ctx.strokeText("java2s.com", 50, 100);
      </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to draw with shadow
Home » Javascript Tutorial » Canvas
Canvas tag
Canvas Context
Rectangle
Rectangle clear
Drawing State
Drawing state restore
Line width
Line Join Style
Line cap settings
Gradients
Linear Gradient
Radial Gradient
Path
Arcs
Two types of curve
Quadratic Bezier Curves
Cubic Bezier Curves
Clip
Text
Shadow
Transparency
Stoke style