canvas中的字体设置比较简单,这里就不说别的了,直接上实例代码:
window.onload=function(){
var myCanvas = document.getElementById("myCanvas");
if(myCanvas.getContext("2d")){
//宽高自适应
//myCanvas.width = document.documentElement.clientWidth-20;
//myCanvas.height = document.documentElement.clientHeight-20;
myCanvas.width = 900;
myCanvas.height = 900;
var context =myCanvas.getContext("2d");
var content = "Canvas学习之文字渲染";
context.font="bold 40px Arial";//设置字体、大小等
//context.textAlign="left";
//使用填充色填充字体
context.fillStyle="#058";//填充颜色
context.fillText("1、填充字体:"+content,40,100);//在(50,100)的位置进行文字渲染
//空心字体(描边)
context.lineWidth=2;
context.strokeStyle="#058";
context.strokeText("2、空心字体:"+content,40,200);
//限制宽度的字体
context.fillText("3、限制宽度(400px):"+content,40,300,400);//最后一个参数用来限制字体显示的宽度
context.strokeText("4、限制宽度(800px):"+content,40,400,800);
//渐变字体
var linearGrad = context.createLinearGradient(0,0,800,0)
linearGrad.addColorStop(0,"black");
linearGrad.addColorStop("0.25","yellow");
linearGrad.addColorStop("0.5","green");
linearGrad.addColorStop("0.75","blue");
linearGrad.addColorStop(1,"black");
context.fillStyle=linearGrad;
context.fillText("5、渐变字体:"+content,40,500);
//图像背景字体
var backgroundImage = new Image();
backgroundImage.src="back.jpg";//使用线性渐变实例中生成的效果图作为背景图
backgroundImage.onload=function(){
var pattern = context.createPattern(backgroundImage,"repeat");
context.fillStyle=pattern;
context.font="bold 100px Arial";
context.fillText("6、背景图字体:"+content,40,600);//填充字体
context.strokeText("6、背景图字体:"+content,40,600);//对已经填充好的字体进行描边
//上面的两个位置必须一致,才能出现既有背景图又有描边效果的字体,否则
//第一个只有填充了背景图的字体,没有描边。第二个没有背景图,只是个空心的即有描边的字体。
};
}else{
return false;
}
}
本文介绍如何在HTML5 Canvas中设置和渲染文字,包括填充、描边、限制宽度及使用渐变和图片背景的文字效果。
6208

被折叠的 条评论
为什么被折叠?



