canvas画布--设置文字
2019年04月16日
844
设置文字
ctx.font = "50px 宋体";
在画布上写一段 50 像素的文本,使用的字体是 "宋体"。
ctx.fillText("愿有人...",60,300);
在画布上写文本。fillText() 方法在画布上绘制填色的文本。文本的默认颜色是黑色。
文本的 x 坐标位置(相对于画布)。
文本的 y 坐标位置(相对于画布)。
ctx.strokeText("愿你成为...",60,400);
在画布上写文本。strokeText() 方法是用来在画布上绘制文本(没有填色)。文本的默认颜色是黑色。
文本的 x 坐标位置(相对于画布)。
文本的 y 坐标位置(相对于画布)。
html
<canvas id="mycan" style="border: 6px solid green;"></canvas>
脚本
<script type="text/javascript">
var mycan = document.getElementById("mycan");
mycan.width = 900;
mycan.height = 900;
var ctx = mycan.getContext("2d");
//写字
ctx.font = "50px 宋体";
ctx.fillText("愿有人陪你颠沛流离",60,300);
ctx.fillText("如果没有",60,350);
ctx.lineWidth = 1;
ctx.strokeText("愿你成为自己的太阳",60,400);
</script>效果

使用渐变填充文本
//创建渐变
var gradient = ctx.createLinearGradient(0,0,mycan.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
//用渐变填色
ctx.fillStyle = gradient;
ctx.fillText("愿有人陪你颠沛流离",60,300);
ctx.fillText("如果没有",60,350);
ctx.strokeStyle = gradient;
ctx.strokeText("愿你成为自己的太阳",60,400);效果

