Enhancing the console.log

Messing around with the console.log and in particular the %c stylized log and tried some experiments and you can enhance the log to render out images etc and in this case I am making a canvas element to hold text and styling it so that the log

And here it is

console.richLog = (textToRender, color) => {
	let renderCanvas = document.createElement('canvas');
	renderCanvas.width = 600;
	const ctx = renderCanvas.getContext("2d");
	ctx.font = "48px serif";
	ctx.background_color = "transparent";
	ctx.fillStyle = (color != null) ? color : "#ff0000";
	ctx.fillText(textToRender, 10, 50);	

	const base64Canvas = renderCanvas.toDataURL("image/png").split(';base64,')[1];
	const newStyle = `font-size:50px;color:transparent;background-image:url('data:image/png;base64,${base64Canvas}');`
	console.log(`%c${".".repeat(textToRender.length + 3)}`, newStyle);	
}

Steps

  • Build a canvas element
  • Render some text on the element
  • Get the base64 data
  • Pop that into a style element
  • Create a text string that here I am sticking transparent . and styling with the background CSS

Complete script

<script>
	console.richLog = (textToRender, color) => {
		let renderCanvas = document.createElement('canvas');
		renderCanvas.width = 600;
		const ctx = renderCanvas.getContext("2d");
		ctx.font = "48px serif";
		ctx.background_color = "transparent";
		ctx.fillStyle = (color != null) ? color : "#ff0000";
		ctx.fillText(textToRender, 10, 50);	
	
		const base64Canvas = renderCanvas.toDataURL("image/png").split(';base64,')[1];
		const newStyle = `font-size:50px;color:transparent;background-image:url('data:image/png;base64,${base64Canvas}');`
		console.log(`%c${".".repeat(textToRender.length + 3)}`, newStyle);	
	}
	
	const logText = "Ultimate power";
	console.richLog(logText);
	console.richLog(logText, "#00ff00");	
</script>

Results

Note

Open Dev Tools console to see what I put on this site