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.
fillText() |
Yes | Yes | Yes | Yes | Yes |
The function call looks like this:
fillText([text],[x],[y],[maxWidth]);
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:
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>