在画布上绘制文字
要在画布上绘制文本,最重要的属性和方法是:
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>
|