This content originally appeared on Bram.us and was authored by Bramus!
One of the things you can do on the DevTools’s Console is style the output for console.log()
and the like:
console.log("%cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
Leveraging this technique, it’s possible to log images to the console:
- Load the image via JS and extract its dimensions
- Expand the box of the logged message by adjusting the
padding
- Set the image as the
background-image
In code:
function getBox(width, height) {
return {
string: "+",
style: "font-size: 1px; padding: " + Math.floor(height/2) + "px " + Math.floor(width/2) + "px; line-height: " + height + "px;"
}
}
console.image = function(url, scale) {
scale = scale || 1;
var img = new Image();
img.onload = function() {
var dim = getBox(this.width * scale, this.height * scale);
console.log("%c" + dim.string, dim.style + "background: url(" + url + "); background-size: " + (this.width * scale) + "px " + (this.height * scale) + "px; color: transparent;");
};
img.src = url;
};
Clever!
Adrian Cooney poored it into a library, which is also capable of auto-generating meme-like images on the console.
This content originally appeared on Bram.us and was authored by Bramus!
Bramus! | Sciencx (2022-02-13T19:33:34+00:00) Log images to the DevTools Console with console.image(). Retrieved from https://www.scien.cx/2022/02/13/log-images-to-the-devtools-console-with-console-image/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.