The 1st note in the importScripts()
function’s documentation explains that the loading of the script(s) is done asynchronously. Which basically mean the web-browser handles the loading of the file(s) in a way that doesn’t halt the execution of other code, like that in the rest of your project’s Story > JavaScript area or that of the engine itself.
So like many things in life, your first issue is likely due to timing. As in you are trying to use the outcome of the file loading (eg. the svg2roughjs variable) before the file has finished being loaded.
To help overcome this issue the function returns a Promise object, which can be used to delay the execution of any code that relies on the successful loading of the file(s) being imported…
importScripts("https://unpkg.com/svg2roughjs/dist/svg2roughjs.umd.min.js")
.then(function () {
/* the script has successfully loaded, do stuff. */
const svgConverter = new svg2roughjs.Svg2Roughjs('#output-div');
svgConverter.svg = document.getElementById('input-svg');
svgConverter.sketch();
})
.catch(function (err) {
/* an error occurred while loading the script, log it. */
console.log(err);
});;
…which fixes the svg2roughjs variable related “not defined” error. However, there is now a “Could not find target in document” related error, which is also due to timing.
In your code example there are two function calls…
svg2roughjs.Svg2Roughjs('#output-div')
document.getElementById('input-svg')
…that search the Document Object Model (DOM) of the page to find specific HTML elements.
eg. one element with an id of output-div, and one element that has a type of input-svg.
However, unless you are creating those elements sometime earlier in your project’s Story > JavaScript area, then neither of those elements will exist because they aren’t part of the SugarCube HTML template.
So there is no point in calling the svg2roughjs related code in the then()
method of the Promise. You will just need to delay the execution of those two functions until after the target elements have been added to the DOM.
The svg2rough.js
project’s documentation becomes very vague at this point, and it expects you to:
- read through the source code of its
/sample-application/
. (which isn’t trivial)
- understand how
svg2rough.js
project makes use of the Rough.js
project’s features.
- [potentially] read parts of the
Rough.js
project’s API documentation.
So while I can explain why you are getting the error (and the follow on one) you had (will have), I found it difficult to provide a working example of using that library in a Twine based project.
Perhaps one of the more advanced/knowledgeable JavaScript users will be able to help you do that.