您好,欢迎访问一九零五行业门户网

如何使用HTML5 canvas绘制文字

使用html5canvas绘制文字的方法:首先创建相应的html示例文件;然后通过filltext方法实现在画布上绘制填色的文本即可。
如果要使用html5 canvas绘制文字,那么需要使用到画布上下文的filltext()方法。下面我们来看具体的内容。
我们先来看具体的示例
<!doctype html><html><head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8"/> <script type="text/javascript"> function draw() { var canvas = document.getelementbyid('simplecanvas'); if ( ! canvas || ! canvas.getcontext ) { return false; } var context = canvas.getcontext('2d'); context.font = 'normal 18pt "楷体"'; context.filltext('hello html canvas world!', 60, 200);} </script></head><body onload="draw()" style="background-color:#d0d0d0;"> <canvas id="simplecanvas" width="640" height="480" style="background-color:#ffffff;"></canvas> <div>canvas demo</div></body></html>
说明:
下面的代码是获取canvas对象并获取上下文。
var canvas = document.getelementbyid('simplecanvas'); if ( ! canvas || ! canvas.getcontext ) { return false; } var context = canvas.getcontext('2d');
下面是绘制字符的代码。指定要在font属性中绘制的字符的字体信息。使用filltext()方法在画布上绘制一个字符串。作为第一个参数绘制的字符串,绘图开始的x坐标和y坐标被赋予第二个和第三个参数。
context.font = 'normal 18pt "楷体"';context.filltext('hello html canvas world!', 60, 200);
运行结果
使用web浏览器显示上述html文件。获得下图的显示结果。
接下来我们来看如何更改文字的颜色
代码如下
<!doctype html><html><head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8" /> <script type="text/javascript"> function draw() { var canvas = document.getelementbyid('simplecanvas'); if ( ! canvas || ! canvas.getcontext ) { return false; } var context = canvas.getcontext('2d'); context.font = 'normal 18pt "楷体"'; context.fillstyle = 'red'; context.filltext('你好,!!!', 60, 200);} </script></head><body onload="draw()" style="background-color:#d0d0d0;"> <canvas id="simplecanvas" width="640" height="360" style="background-color:#ffffff;"></canvas> <div>canvas demo</div></body></html>
说明:
更改文本颜色,需要设置fillstyle属性为文本颜色。
context.font = 'normal 18pt "楷体"'; context.fillstyle = 'red'; context.filltext('你好,!!!', 60, 200);
运行结果:
使用web浏览器显示上述html文件。将获得如下图所示的效果,已绘制了红色的字体。
以上就是如何使用html5 canvas绘制文字的详细内容。
其它类似信息

推荐信息