CanvasRenderingContext2D提供了fillText方法,使我们可以在Canvas上绘制文字。可以通过CanvasRenderingContext2D的font属性来设置文字的fontSize、是否加粗及字体属性等。
在这个实验中,尝试在Canvas中绘制一个具有立体感文字特效。看下面的代码:
你的浏览器不支持canvas
var c = document.getElementById("myCanvas");
var cxt = c.getContext("2d");
cxt.fillStyle = "#0f0";
var fontSize = 90;
cxt.font = "bold 90px Arial";
cxt.fillText("立", 190, 90);
cxt.globalAlpha = 0.7;
cxt.font = "bold 70px Arial";
cxt.fillText("体", 260, 90);
cxt.globalAlpha = 0.6;
cxt.font = "bold 50px Arial";
cxt.fillText("感", 310, 90);
cxt.globalAlpha = 0.5;
cxt.font = "bold 30px Arial";
cxt.fillText("文", 350, 90);
cxt.globalAlpha = 0.4;
cxt.font = "bold 20px Arial";
cxt.fillText("字", 370, 90);
cxt.globalAlpha = 0.7;
cxt.font = "bold 70px Arial";
cxt.fillText("体", 145, 90);
cxt.globalAlpha = 0.6;
cxt.font = "bold 50px Arial";
cxt.fillText("感", 110, 90);
cxt.globalAlpha = 0.5;
cxt.font = "bold 30px Arial";
cxt.fillText("文", 90, 90);
cxt.globalAlpha = 0.4;
cxt.font = "bold 20px Arial";
cxt.fillText("字", 80, 90);
通过设置字体的大小、透明度来实现立体层次感。其中CanvasRenderingContext2D的globalAlpha属性用来设置透明度。其中为0到1,当CanvasRenderingContext2D.globalAlpha为0时完全透明,当CanvasRenderingContext2D.globalAlpha为1时,完全不透明。
最终的效果如下所示: