HTML5 Canvas Reference - fillText()








The context.fillText() function draws render solid-colored text to the canvas.

The color used is set in the context.fillColor property.

The font used is set in the context.font property.

Browser compatibility

fillText() Yes Yes Yes Yes Yes

Javascript Syntax

The function call looks like this:

Parameter Values

fillText([text],[x],[y],[maxWidth]);
  • text - The text to render on the canvas.
  • x - The x position of the text on the canvas.
  • y - The y position of the text on the canvas.
  • maxWidth - The maximum width of the text as rendered on the canvas.




Example

The following code draws the string on the canvas.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--   ww  w  .  j  a  va 2s  .  co  m-->
    var canvas = document.getElementById("myCanvas"),
    ctx = canvas.getContext("2d");
    ctx.font="50px Arial";
    ctx.fillText("Java2s.com", 0,100);

</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code draws text with gradient color.

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--  w w  w .  ja v a2 s .c  o  m-->
    var canvas = document.getElementById("myCanvas"),
    ctx = canvas.getContext("2d");

    ctx.font = "50px Verdana";
    
    // Create gradient
    var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
    gradient.addColorStop("0", "blue");
    gradient.addColorStop("0.5", "yellow");
    gradient.addColorStop("1.0", "red");
    
    // Fill with gradient
    ctx.fillStyle = gradient;
    ctx.fillText("java2s.com", 0, 100);
</script>
</body>
</html>

Click to view the demo