We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
I wrote a very basic html document and am trying to use JavaScript to dynamically add the elements that would run a Processing sketch with processing.js.
I'm adding a script element that points to processing.js, and adding it to the document's head. Then I'm creating a canvas that points to my sketch, and adding it to a div in the body. They seem to be added in the dom ok when I check inspect from a browser, but the sketch doesn't run. If I directly write those 2 elements inside the document, then it works fine, so I'm not sure if something's not evaluating, or evaluating out of order, and so on.
I should note that I am running this on a local server. I was able to get this to work easily with p5.js, but hoping I can get it for processing.js too because most of my 3d sketches uses it! I broke it down to a simple example so you can check my code below.
<html lang="en-US">
<head>
<!-- Works if I uncomment this!
<script type="text/javascript" src="resources/libs/processing.js"></script>
-->
</head>
<body>
<div id="sketchContainer">
<!-- Works if I uncomment this!
<canvas data-processing-sources="js/header_sketches/my_awesome_sketch.js"></canvas>
-->
</div>
<script>
var scrElt = document.createElement("script");
scrElt.type = "text/javascript";
scrElt.src = "resources/libs/processing.js";
scrElt.async = false;
scrElt.onload = function() {
var canvas = document.createElement("canvas");
canvas.setAttribute("data-processing-sources", "js/header_sketches/my_awesome_sketch.js");
document.getElementById("sketchContainer").appendChild(canvas);
};
document.head.appendChild(scrElt);
</script>
</body>
</html>
Answers
Hmm... Still not good w/ DOM stuff. But my hunch is that right after "processing.js" is loaded & executed, it searches for some
<canvas>
w/ data-processing-sources attribute on it.If none's found at that time, nothing happens! :|
Seems like you only create your
<canvas>
onLoad(). Maybe it's too l8 for that then? :-??Just did a test but creating canvas before still doesn't seem to work. But if I hardcode processing.js to be in there then have JavaScript create the canvas it works. I think that's why I was trying to use onLoad() in the first place. Just can't seem to get both of them working in pure JavaScript!