This post walks through how to add an HTML Canvas to a Hugo site, with additional guidance on including external JavaScript libraries from a CDN, such as Three.js to render the cube shown below:
Hugo Shortcodes
Adding support to a new HTML DOM in your Hugo site is possible using Hugo shortcodes. Which is a way to add custom HTML elements to your website like image, video, and HTML canvas. The shortcode is a HTML template invoked within markup, accepting any number of arguments.
To create a new shortcode, just create a new file at layouts/_shortcodes/myshortcode.html.
Now you can invoke that shortcode from your markdown using the following syntax:
| |
Hugo will replace that call with the content of your shortcode.
Sending data from markdown to HTML
From the markdown, you can pass multiple params to the shortcode. Each param can be string, integer, floating point, or boolean.
For example
| |
Built-in Shortcodes
Note that Hugo comes with some built-in shortcodes like that are ready to be used.
| |
But we don’t have one for canvas yet, so we need to create our own.
Canvas Shortcode
Create a new shortcode called canvasjs and add the following content:
| |
Now we can invoke the canvas from the markdown using the following syntax:
| |
We also need to create the script test1.js.
To do that, create a new scripts/test1.js file at same level as your markdown file with the following content:
| |
Resulting in:
And we are done.
Three.js & Importmaps
Libraries like Three.js goes well with HTML canvas.
To use such library, we can create a new shortcode that creates a importmap which allow you to use the import module syntax inside your script.
Create a new shortcode at layouts/_shortcodes/importmap.html with the following content:
| |
The importmap must be the first <script> parsed by the browser.
So the invokation of the shortcode should be the first thing in your markdown file.
Just invoke it like we did with the canvasjs passing the library version as parameter:
| |
Now just call the same canvas shortcode we created earlier
| |
Inside the sphere1.js we can just import three like a module:
| |
Resulting: