JSFiddle - React, Tailwind, and code Playground
by Gwyn Milcote
HTML
Watermarking example. After each image has been lazy-loaded, replace it with a canvas with text added.
<hr>
<img id='img1' class='small' src='http://www.pigeonbob.com/tangpearl.jpg' data-wmark="Tangerine Pearl - PigeonBob.com" loading='lazy' onload='wmark(1)'>
<img id='img2' style='width: 50%; height: auto;' src='http://www.dovepage.com/species/domestic/Ringneck/colors/tangerine-pearl.jpg' data-wmark="Tangerine Pearl - dovepage.com" loading='lazy' onload='wmark(2)'>
<img id='img3' style='height: 222px; width: auto;' src='https://i.pinimg.com/originals/01/e0/f5/01e0f5228fbd3b03e4a5ba8b805088db.jpg' data-wmark="Darn Pinterest! Real source unknown" loading='lazy' onload='wmark(3)'>
<div id='test'>
<img id='img4' src='http://www.backyardbirdcam.com/gallery/dove-peach-lg1.jpg' data-wmark="Peach? - BackyardBirdcam.com" loading='lazy' onload='wmark(4)'>
</div>
<img id='img5' src="http://www.ringneckdove.com/Wilmer's%20WebPage/Picture_doves/777N%20mandatory%20tangerine.jpg" data-wmark="Tangerine - Wilmer Fuller (ringneckdove.com)" loading='lazy' onload='wmark(5)'>
CSS
canvas {
border: 1px solid green;
}
/* Various ways to set the size of images */
img {
width: 100%;
max-width: 800px;
height: auto;
}
.small {
max-width: 300px;
height: auto;
}
#test img {
width: 250px;
height: 230px;
}
JavaScript
function wmark(id){
// return;
// Return, to see the images load normally.
let img = document.querySelector("#img" + id);
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
// Copy image's visual size on the page.
canvas.height = img.offsetHeight;
canvas.width = img.offsetWidth;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Add the semi-opaque rectangle across bottom.
ctx.globalAlpha = 0.7;
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, canvas.height - 25, canvas.width, 25);
ctx.globalAlpha = 1.0;
// And write the text, centered near the bottom.
ctx.font = "14px Arial";
ctx.fillStyle = "#000000";
ctx.textAlign = "center";
ctx.fillText(img.dataset.wmark, canvas.width / 2, canvas.height - 7);
// Put canvas exactly where the image was.
let parent = img.parentNode;
parent.replaceChild(canvas, img);
}