Skip to content

Instantly share code, notes, and snippets.

@0xadada
Created September 10, 2019 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xadada/93343a661494622ec61c6e7c99bf5ef4 to your computer and use it in GitHub Desktop.
Save 0xadada/93343a661494622ec61c6e7c99bf5ef4 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Placeholder</title>
<img data-size="150x300" alt="Asian" data-show-markup>
<img data-size="150x300" alt="Bengal">
<script src="placeholder.js"></script>
</html>
(function() {
/* given a selector, initialize a placeholder image base on the data-size
* attribute, given format "<width>x<height>"
*/
function init(selector) {
let domImages = document.querySelectorAll(selector);
for (var i = 0; i < domImages.length; i++) {
let img = domImages[i];
let textArea = document.createElement("textarea");
let [width, height] = img.getAttribute("data-size").split("x");
let desc = `${img.alt}: ${width}x${height}`;
img.title = desc;
img.src = generatePlaceholder(height, width, img.id, desc);
if (img.getAttribute("data-show-markup") !== null) {
// insert textarea after img
textArea.value = img.outerHTML;
img.parentNode.insertBefore(textArea, img.nextSibling);
}
}
}
/* generatePlaceholder renders an SVG document given a height, width, a
* color character, and a text label.
* @returns String
*/
function generatePlaceholder(height, width, id, text) {
let x = Number.parseInt(width, 10);
let y = Number.parseInt(height, 10);
let svg = `<svg width="${x}" height="${y}" xmlns="http://www.w3.org/2000/svg">
<rect x="2" y="2" width="${x - 4}" height="${y -
4}" style="fill:#DEDEDE;stroke:#555555;stroke-width:1"/>
<text x="50%" y="50%" font-size="12" text-anchor="middle" alignment-baseline="middle" font-family="sans-serif" fill="#555555">
${text}
</text>
</svg>`;
return dataUriForString(svg);
}
/* dataUriForXY
* given a width and height, construct and return return a data URI for an
* SVG placeholder image.
*/
function dataUriForString(data) {
const base64Data = btoa(data);
return `data:image/svg+xml;base64,${base64Data}`;
}
// start
init("img[data-size]");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment