Text can be added to the canvas. First you need to set a font in the graphics context. This is another thing that the context keeps hold of. Then position a string of text like this:
g2.font = "24px sans-serif";
g2.fillText("Some text", xLeft + 8, yTop + 24);
There is also g2.strokeText()
(with the same parameters) if you want to show characters in outline, or perhaps to add a differently coloured outline for contrast against a busy background.
Images can also be drawn on the canvas but first they must be loaded from files. That is more complicated because loading happens as a parallel process and we need to be sure the loading has completed before trying to draw the image. Here is the simplest way of doing it but we will look at it again in more detail later (in section 4).
function loadImage(filePath)
{
let im = new Image();
im.loaded = false;
im.onerror = function()
{
alert('Failed to load ' + filePath);
};
im.onload = function()
{
im.loaded = true;
};
im.src = filePath;
return im;
}
Call that in the initial run()
function and save the returned image somewhere (details later) so that later we can do this:
if (im.loaded)
{
g2.drawImage (im, x, y, width, height);
}
The parameters width and height need not be the original size of the image. Scaling happens automatically, which is very useful for drawing scenes. More details in section 4.