If you're not looking to display an actual image, you can retrieve your code and enclose it within
<pre><code></code></pre>
tags. Make sure to set the z-index lower than your main content.
<pre style="position:absolute; z-index:1; pointer-events:none;"><code></code></pre>
<div style="position:relative; z-index:2;"></div>
<script>
fetch('/yourscript.js').then(response=>response.text()).then(text=>{
document.querySelector('code').innerText = text;
});
</script>
You can customize it by setting properties like width/height and font-size as needed.
If you want to utilize it as a background image, then creating an <svg>
with <foreignObject>
is required. This allows you to generate object URLs for use.
- Retrieve your code
- Construct the appropriate svg XML, placing your code in the correct location, such as inside a
<pre>
tag within <foreignObject>
.
- Use the xml to create a blob with mime type
image/svg+xml
- Generate an object URL from that blob. This URL can then serve as an alternative to a typical image URL.
fetch('/yourscript.js').then(response=>response.text()).then(text=>{
var data = `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="500">
<foreignObject width="100%" height="100%">
<pre xmlns="http://www.w3.org/1999/xhtml">
<code>${text}</code>
</pre>
</foreignObject>
</svg>`;
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = window.URL.createObjectURL(svg);
document.body.style.backgroundImage = `url(${url})`;
});
Note the width/height attributes of the <svg>
, any content outside those dimensions will not be visible, so ensure they are suitable for your intended display.
If you desire an actual image file, you can use that object URL as the src for an Image
, draw it on a <canvas>
, and utilize toDataURL
To achieve text highlighting akin to your example image, additional steps are necessary, such as styling specific elements around the desired text before application.