使用 DOM API(带有图形文本 Canvas SVG 或图像文件)

使用 canvas 元素

HTML 提供了用于构建基于栅格的图像的 canvas 元素。

首先构建一个用于保存图像像素信息的画布。

var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 250;

然后选择画布的上下文,在本例中为二维:

var ctx = canvas.getContext('2d');

然后设置与文本相关的属性:

ctx.font = '30px Cursive';
ctx.fillText("Hello world!", 50, 50);

然后将 canvas 元素插入页面以使其生效:

document.body.appendChild(canvas);

使用 SVG

SVG 用于构建可缩放的基于矢量的图形,可以在 HTML 中使用。

首先创建一个尺寸为 SVG 的元素容器:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.width = 500;
svg.height = 50;

然后构建一个具有所需定位和字体特征的 text 元素:

var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('x', '0');
text.setAttribute('y', '50');
text.style.fontFamily = 'Times New Roman';
text.style.fontSize = '50';

然后添加实际文本以显示到 textelement:

text.textContent = 'Hello world!';

最后将 text 元素添加到 svg 容器中,并将 svg 容器元素添加到 HTML 文档中:

svg.appendChild(text);
document.body.appendChild(svg);

图像文件

如果你已有包含所需文本的图像文件并将其放在服务器上,则可以添加图像的 URL,然后将图像添加到文档中,如下所示:

var img = new Image();
img.src = 'https://i.ytimg.com/vi/zecueq-mo4M/maxresdefault.jpg';
document.body.appendChild(img);