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.
(via Stefan)
Is this still possible with the new versions of chrome?