If you do not need an actual image, you can fetch your code and wrap it in <pre><code></code></pre>
. Then set it to a lower z-index 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 would need to stylize it as needed, eg setting width/height, font-size
If you want to be able to use it as an actual background, then you would need to use <svg>
with the use of <foreignObject>
. After which you can use to create object urls.
- Fetch your code
- Build the correct svg XML, inserting your code into the correct place, eg inside a
<pre>
tag within <foreignObject>
.
- Then using that xml create a blob with mime type
image/svg+xml
- Finally create an object url from that blob. The url then can be used in place of an actual 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>
, anything drawn outside of those dimensions will not be seen, so use the appropriate values for your targets.
And if you wanted an actual image file you could just then use that object url as the src for an Image
, draw it on a <canvas>
and call toDataURL
For the actual text highlighting (like that in your example image) you would need to do extra work, like wrapping the correct text in styled elements before using it.