I am trying to generate an image using p5.js and p5.js-svg and then save the SVG xml as a dataURL for storage. Here is an example script that I've simplified for this question:
const canvasWidth = 600;
const canvasHeight = 600;
const bgColor = "#fffcf3";
let unencodedDataURL = "";
const sketch = (p) => {
p.setup = () => {
p.createCanvas(canvasWidth, canvasHeight, p.SVG);
p.background(bgColor);
p.noLoop();
}
p.draw = () => {
p.noFill();
p.ellipse(z
canvasWidth / 2,
canvasHeight / 2,
150,
150
);
unencodedDataURL = p.getDataURL();
console.log(`inside: ${unencodedDataURL}`);
}
}
const test = new p5(sketch, document.body);
console.log(`outside: ${unencodedDataURL}`);
The first log statement prints the right dataURL. But of course the second log statement executes before the one inside draw() and I cannot figure out how to capture the dataURL correctly. I'm sure I am missing something in the p5.js or p5.js-svg libraries and there is an easier way. But I am stuck. Anyone have an idea here? Thanks in advance!
Because p5js run asynchronous, You can add callback or write a Promise to get data after sketch draw, like this
var handleDataCallback = null;
//........
p.ellipse(
canvasWidth / 2,
canvasHeight / 2,
150,
150
);
unencodedDataURL = p.getDataURL();
if (handleDataCallback) handleDataCallback(unencodedDataURL);
//....
//for callback
handleDataCallback = dataURL => {
//todo something with dataURL
}
if you want to write as a function to generate image
function generateImage(param, callback) {
return new Promise(resolve => {
//......
// do something
p.ellipse(
canvasWidth / 2,
canvasHeight / 2,
150,
150
);
var unencodedDataURL = p.getDataURL();
if (callback) callback(unencodedDataURL);
resolve(unencodedDataURL);
// ....
})
}
//use Promise
generateImage(yourParam, null).then(unencodedDataURL=>{
console.log(`outside: ${unencodedDataURL}`);
})
//or callback
generateImage(yourParam, unencodedDataURL=> {
console.log(`outside: ${unencodedDataURL}`);
});