概念:
在HTML5中可以在Canvas画布中进行文字的绘制,
发同时也可以指定绘制文字的字体、大小、对齐方式等,还可以进行文字的纹理填充。。
绘制文字时可以使用fillText方法或strokeText方法:
前者用填充方式绘制字符串
void fillText(text,x,y,[maxWidth]);
第一个参数表示要绘制的文字,第二个参数表示要绘制文字的起点横坐标,第三个参数表示要绘制文字的起点纵坐标,第四个参数表示可选参数,表示显示文字时的最大宽度。
后者用轮廓方式绘制字符串。
void strokeText(text,x,y,[maxWidth]);
在shiy Canvas API来进行文字的绘制之前,可以先对该对象的有关文字绘制的属性进行设置,他们是:
textAlign属性:设置文字水平对齐方式,属性值可以为start、end、left、right、center。默认值为start。
textBaseline属性:设置文字垂直对齐方式,属性值可以为top、hanging、middle、alphabetic、ideographic、bottom。默认值为alphabetic
应用:
完整代码
<html>
<head>
<title></title>
<style type="text/css">
#myCanvas{
border: 1px solid blue;
background-color: #77ffcc;
}
</style>
<script type="text/javascript">
window.onload=function(){
var canvas=document.getElementById("myCanvas");
if(canvas==null)
return false;
var context = canvas.getContext(‘2d‘);
context.fillStyle = "#0000ff";
context.font = ‘italic 30px sans-serif‘;
context.textBaseline = ‘top‘;
//填充字符串
context.fillText(‘示例文字‘,0);
context.font = ‘bold 30px sans-serif‘;
//轮廓字符串
context.strokeText(‘示例文字‘,50);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="500" height="200"></canvas>
</body>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。