Home >Web Front-end >HTML Tutorial >How to use canvas in HTML5 to achieve the effect of gradient text
Use the canvas in HTML5 to achieve the gradient text effect. The syntax and parameter settings required are as follows. Friends who are unclear can take a look.
1. fillText( )
Syntax: context.fillText(text,x,y,maxWidth)
text indicates that it needs to be output on the canvas The text
x represents the X-axis coordinate where the text starts to be drawn
y represents the Y-axis coordinate where the text starts to be drawn
maxWidth represents the maximum text width allowed, the unit is pixels, and is an optional value.
2. createLinearGradient( )
Syntax: context.createLinearGradient(x0,y0,x1,y1)
x0 represents the X of the gradient starting point Axis coordinate
y0 represents the Y-axis coordinate of the gradient start point
x1 represents the X-axis coordinate of the gradient end point
y1 represents the Y-axis coordinate of the gradient end point
Example: 1 : Make a normal text (no color gradient), the code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #ccc;"></canvas> </body> <script type="text/javascript"> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.font="20px Georgia"; ctx.fillText("学习使我快乐",10,50); </script> </html>
The effect picture is as shown:
Example 2: Make a gradient text , the specific code is as follows:
ctx.font="30px Verdana"; // Create gradient var gradient=ctx.createLinearGradient(0,0,c.width,0); gradient.addColorStop("0","orange"); gradient.addColorStop("0.5","blue"); gradient.addColorStop("1.0","red"); // Fill with gradient ctx.fillStyle=gradient; ctx.fillText("have a nice day ",10,100);
Rendering:
When making gradient text, first use createLinearGradient() to create a gradient, and then use fillStyle to change the gradient Apply to text.
The above introduces how to use canvas in HTML5 to create gradient text effects. It is simple and practical. Beginners can practice it by themselves. I hope you can create more cool effects.
For more related courses, please visit Html5 video tutorial
The above is the detailed content of How to use canvas in HTML5 to achieve the effect of gradient text. For more information, please follow other related articles on the PHP Chinese website!