本文原文地址:https://www.jeremyjone.com/485/, 转载请注明,谢谢。
在canvas
中,为我们提供了一个非常方便的添加文字的方法,直接上 w3school 的文档说明:
context.fillText(text,x,y,maxWidth);
// text: 规定在画布上输出的文本。
// x: 开始绘制文本的 x 坐标位置(相对于画布)。
// y: 开始绘制文本的 y 坐标位置(相对于画布)。
// maxWidth: 可选。允许的最大文本宽度,以像素计。
官方也给我们提供了一个简单的说明:
使用 fillText(),在画布上写文本 “Hello world!” 和 “w3school.com.cn”:
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("w3school.com.cn",10,90);
根据文档说明,可以很清楚fillText()
的具体用法,那么接下来就来绘制我们自定义的文本。
在绘制之前,我们需要清楚,网页中的文字都是由输入框来交互的,canvas
并不具备这样的功能,所以,我们先简单写一个具有canvas
、input
框和一个按钮页面,来模拟我们的效果。
其实,从这里就可以看出绘制文字的思路,这和我们平时的截图功能大致一样。
实际测试地址:点击这里开始测试
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JS - Canvas - texttitle>
head>
<body style="background-color: #999">
<div>
<canvas id="canvas" width="800" height="200" style="background-color: #fff">抱歉,您的浏览器不支持canvas元素canvas>
div>
<textarea name="textBox" id="textBox" cols="30" rows="10" c