小码哥的IT人生

HTML canvas fillText() 方法 详解

HTML基础 2022-06-02 15:27:17小码哥的IT人生shichen

HTML canvas fillText() 方法

定义和用法

fillText() 方法在画布上绘制填色的文本。文本的默认颜色是黑色。

提示:请使用 font 属性来定义字体和字号,并使用 fillStyle 属性以另一种颜色/渐变来渲染文本。

实例

使用 fillText(),在画布上写文本 "Hello world!" 和 "www.phpcodeweb.com":

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Georgia";
ctx.fillText("Hello World!",10,50);
ctx.font="30px Verdana";
// 创建渐变
var gradient=ctx.createLinearGradient(0,0,c.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// 用渐变填色
ctx.fillStyle=gradient;
ctx.fillText("www.phpcodeweb.com",10,90);

 

完整实例【亲自试一试】:

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="20px Georgia";
ctx.fillText("Hello World!",10,50);
ctx.font="30px Verdana";
// Create gradient
var gradient=ctx.createLinearGradient(0,0,c.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","red");
// Fill with gradient
ctx.fillStyle=gradient;
ctx.fillText("www.phpcodeweb.com",10,90);
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

语法

context.fillText(text,x,y,maxWidth);

参数值

参数 描述
text 规定在画布上输出的文本。
x 开始绘制文本的 x 坐标位置(相对于画布)。
y 开始绘制文本的 y 坐标位置(相对于画布)。
maxWidth 可选。允许的最大文本宽度,以像素计。

浏览器支持

表中的数字注明了首个完全支持该属性的浏览器版本。

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

注释:Internet Explorer 8 以及更早的版本不支持 <canvas> 元素。

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024