fillText() Method - Javascript Canvas Reference

Javascript examples for Canvas Reference:fillText

Description

The fillText() method draws filled text. The default color is black.

JavaScript syntax

context.fillText(text, x, y, maxWidth);

Parameter Values

Parameter Description
text text to draw
x The x coordinate where to start
y The y coordinate where to start
maxWidth Optional. The maximum allowed width of the text, in pixels

The following code shows how to write "Hello world!" and "from java2s.com" with gradient on the canvas.

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="250" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.font = "20px Georgia";
ctx.fillText("Hello World!", 10, 50);

ctx.font = "30px Verdana";
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.fillStyle = gradient;/* ww  w  .  j av  a 2 s. c  om*/
ctx.fillText("from java2s.com", 10, 90);

</script>

</body>
</html>

Related Tutorials