Using the DOM API with graphical text Canvas SVG or image file

suggest change

Using canvas elements

HTML provides the canvas element for building raster-based images.

First build a canvas for holding image pixel information.

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

Then select a context for the canvas, in this case two-dimensional:

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

Then set properties related to the text:

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

Then insert the canvas element into the page to take effect:

document.body.appendChild(canvas);

Using SVG

SVG is for building scalable vector-based graphics and can be used within HTML.

First create an SVG element container with dimensions:

width and height on an SVG element are animated lengths, not ordinary number properties. Set them as attributes. These snippets also need document.body.

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

Then build a text element with the desired positioning and font characteristics:

const 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 = '50px';

Then add the actual text to display to the text element:

text.textContent = 'Hello world!';

Finally add the text element to our svg container and add the svg container element to the HTML document:

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

Image file

If the text is already in an image file on a server, set the image URL and append the element. The address below is only an example:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents