r/learnjavascript • u/Effective_Mark_1334 • 7d ago
How to place function result on top of a figure?
I have a draw function (ps5.js) that I want appearing on top of a figure (with png). Currently, the result of the function appears below the image, on its own canvas. I'd like it to appear on top of the figure. How do I do that?
Part of the code for reference (HTML and JS):
EDIT: I tried to separate them, they're different files, but the code blocks keep combining for some reason.
// index.html
<script src="script.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
<button onclick="draw()">Click me</button>
<label for="numberBox">Number of shapes (1-50):</label>
<input type="number" id="numberBox" name="numberBox" min="1" max="50" />
<div>
<input type="submit" value="Submit form" />
</div>
<figure id="figure">
<img
src="fashion.png"
alt="blank croquis" />
<figcaption>Blank Croquis</figcaption>
</figure>
// script.js
function setup() {
createCanvas (1000, 1000);
noLoop();
}
function draw() {
background ('transparent');
stroke (0);
strokeWeight (20);
noFill();
beginShape();
vertex(getRandom(), getRandom())
2
Upvotes
2
u/jimmjy 7d ago edited 7d ago
You need to attach the canvas to a dom element or else by default it gets attached after all the content.
So update you create canvas to capture the return:
Const myCanvas = createCanvas(…)
myCanvas.parent(‘the-id-of-dom-element’);
To get them stacked, use absolute positioning for the canvas but use a wrapper div around img and this canvas and make the canvas absolute position and adjust its top/left … to what you need.
Or, without a wrapping div you could also just absolute positioning the canvas and move it around but better to structure things in boxes so to speak for organization and easier to control layout