AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > html游戏

HTML画布文本-填充文本、不填充文本、文本居中并填颜色

51自学网 http://www.51zixue.net

 在画布上绘制文字

要在画布上绘制文本,最重要的属性和方法是:
 
font - 定义文本的字体属性
fillText(text,x,y) - 在画布上绘制“填充”文本
strokeText(text,x,y) - 在画布上绘制文本(不填充)
 
使用fillText()
将字体设置为30px“Arial”并在画布上写入一个填充的文本:

JavaScript:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
注释:(10,50)为文字的起始点坐标,第一个绘制文字的左下角点坐标。
完整代码:
<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
</script>

</body>
</html>
使用strokeText()
将字体设置为30px“Arial”,并在画布上写入无填充的文本:

JavaScript:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);
添加颜色和设定文本居中
将字体设置为30px“Comic Sans MS”,并在画布的中央写一个填充的红色文本:

JavaScript:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2); 
完整代码:
<!DOCTYPE html>
<html>
<body>

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

<script>
var canvas = document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
ctx.font="30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);
</script>

</body>
</html>

 
上一篇:HTML画布渐变  下一篇:返回列表