Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elmariachi111/9dd638db2e757586943a96fa98ecae5d to your computer and use it in GitHub Desktop.
Save elmariachi111/9dd638db2e757586943a96fa98ecae5d to your computer and use it in GitHub Desktop.
Chatgpt render and export p5 image
Stefan Adolf
Write a JavaScript program that renders a p5js image of a flower inside a browser context
Sure, here's an example of how to render a flower using p5js in a browser context:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Flower</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
</style>
</head>
<body>
<script>
function setup() {
createCanvas(400, 400);
}
function draw() {
background(255, 255, 200);
noStroke();
fill(255, 0, 0);
translate(width/2, height/2);
for (let i = 0; i < 10; i++) {
rotate(TWO_PI / 10);
ellipse(50, 0, 20, 60);
}
fill(255, 255, 0);
ellipse(0, 0, 50, 50);
}
new p5(null, 'flower');
</script>
<div id="flower"></div>
</body>
</html>
In this example, we're using a CDN-hosted version of p5js to load the library. We define a setup function that creates a canvas with dimensions of 400x400, and a draw function that draws the flower. We use the noStroke() function to remove the stroke from the petal ellipses, and the translate() function to center the flower on the canvas. We then use a loop to draw the 10 petals, rotating each time to get the correct placement. Finally, we draw a yellow circle in the center of the flower using fill() and ellipse().
To run this program, simply save it to a file with a .html extension and open it in your web browser.
Stefan Adolf
Great, now wrap the above script in a headless browser context that contains a function interface to export the rendered p5 image as a png file.
Sure, here's an example of how to wrap the previous script in a headless browser context using Node.js and Puppeteer, and add a function to export the rendered p5 image as a PNG file:
javascript
Copy code
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Flower</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
</style>
</head>
<body>
<script>
function setup() {
createCanvas(400, 400);
}
function draw() {
background(255, 255, 200);
noStroke();
fill(255, 0, 0);
translate(width/2, height/2);
for (let i = 0; i < 10; i++) {
rotate(TWO_PI / 10);
ellipse(50, 0, 20, 60);
}
fill(255, 255, 0);
ellipse(0, 0, 50, 50);
}
new p5(null, 'flower');
</script>
<div id="flower"></div>
</body>
</html>
`;
await page.setContent(htmlContent);
await page.waitForSelector('#flower canvas');
const screenshotOptions = {
type: 'png',
fullPage: true,
encoding: 'binary'
};
const screenshotBuffer = await page.screenshot(screenshotOptions);
await browser.close();
// Function to export the screenshot buffer as a PNG file
const fs = require('fs');
function exportImage(buffer, fileName) {
fs.writeFileSync(fileName, buffer, 'binary');
}
exportImage(screenshotBuffer, 'flower.png');
})();
In this example, we're using Puppeteer to launch a headless browser, create a new page, set the HTML content to our p5js script, and wait for the canvas to be rendered. We then take a screenshot of the entire page as a PNG buffer using the page.screenshot() method, and close the browser.
Finally, we define a function called exportImage() that takes the screenshot buffer and a file name as arguments, and writes the buffer to a file using the Node.js fs module.
To run this program, save it to a file with a .js extension and run it using Node.js (node filename.js). The exported PNG file will be saved in the same directory as the script.
Stefan Adolf
Fine, now modify the above code to take arbitrary p5js code as a parameter and executes it inside the puppeteer context
Sure, here's an updated example of how to modify the previous code to take arbitrary p5js code as a parameter and execute it inside the Puppeteer context:
javascript
Copy code
const puppeteer = require('puppeteer');
async function generateImageFromP5Code(p5Code, outputFileName) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>P5js</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
</style>
</head>
<body>
<script>
${p5Code}
</script>
<div id="p5js"></div>
</body>
</html>
`;
await page.setContent(htmlContent);
await page.waitForSelector('#p5js canvas');
const screenshotOptions = {
type: 'png',
fullPage: true,
encoding: 'binary'
};
const screenshotBuffer = await page.screenshot(screenshotOptions);
await browser.close();
// Function to export the screenshot buffer as a PNG file
const fs = require('fs');
function exportImage(buffer, fileName) {
fs.writeFileSync(fileName, buffer, 'binary');
}
exportImage(screenshotBuffer, outputFileName);
}
const p5Code = `
function setup() {
createCanvas(400, 400);
}
function draw() {
background(255, 255, 200);
noStroke();
fill(255, 0, 0);
translate(width/2, height/2);
for (let i = 0; i < 10; i++) {
rotate(TWO_PI / 10);
ellipse(50, 0, 20, 60);
}
fill(255, 255, 0);
ellipse(0, 0, 50, 50);
}
new p5(null, 'p5js');
`;
generateImageFromP5Code(p5Code, 'flower.png');
In this updated example, we define a new function called generateImageFromP5Code() that takes two parameters: p5Code, which is a string containing the arbitrary p5js code to execute, and outputFileName, which is the name of the PNG file to export.
We modify the HTML content to include the p5Code parameter as the script to execute, and update the selector in the page.waitForSelector() method to wait for the #p5js div instead of the #flower div.
Finally, we define a new p5Code variable containing the arbitrary p5js code to execute, and call the generateImageFromP5Code() function with the p5Code and outputFileName parameters.
To run this program, save it to a file with a .js extension and run it using Node.js (node filename.js). The exported PNG file will be saved in the same directory as the script.
Stefan Adolf
Now, build a dockerfile with a base image that allows executing above code as a container and make the p5js code that’s used as input a variable that‘s provided to the container when it starts. Export the generated png file so I can reuse it outside of the container.
Sure, here's an example Dockerfile that builds an image containing the Puppeteer environment and a script that takes a p5js code string as a command-line argument, generates an image using the code, and exports it to a mounted directory outside the container:
dockerfile
Copy code
FROM node:16-slim
# Install dependencies
RUN apt-get update && apt-get install -y \
ca-certificates \
fonts-liberation \
gconf-service \
libappindicator1 \
libasound2 \
libatk1.0-0 \
libcairo2 \
libcups2 \
libdbus-1-3 \
libexpat1 \
libfontconfig1 \
libgbm1 \
libgcc1 \
libgconf-2-4 \
libgdk-pixbuf2.0-0 \
libglib2.0-0 \
libgtk-3-0 \
libnspr4 \
libnss3 \
libpango-1.0-0 \
libpangocairo-1.0-0 \
libstdc++6 \
libx11-6 \
libx11-xcb1 \
libxcb1 \
libxcomposite1 \
libxcursor1 \
libxdamage1 \
libxext6 \
libxfixes3 \
libxi6 \
libxrandr2 \
libxrender1 \
libxss1 \
libxtst6 \
lsb-release \
wget \
xdg-utils \
&& rm -rf /var/lib/apt/lists/*
# Create app directory
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install app dependencies
RUN npm install
# Copy app files
COPY . .
# Expose port for incoming connections (not required for this example)
EXPOSE 3000
# Define entrypoint command that takes a p5js code string as a command-line argument and generates an image using the code
ENTRYPOINT ["node", "generate-image.js"]
# Define default command to execute when the container is started
CMD ["", "/output/image.png"]
To build and run this container, you can use the following commands:
bash
Copy code
# Build the Docker image (replace `image-name` with your desired image name)
docker build -t image-name .
# Run the Docker container, providing the p5js code as a command-line argument and mounting a directory to export the generated image (replace `p5js-code-string` and `/output/directory` with your desired values)
docker run -v /output/directory:/app/output image-name "p5js-code-string" /output/image.png
In this example, we define the entrypoint command to execute the generate-image.js script, which takes two command-line arguments: the p5Code parameter (provided as the first argument) and the outputFileName parameter (provided as the second argument).
We use the ENTRYPOINT keyword to define the entrypoint command and the CMD keyword to define the default command to execute when the container is started. We also use the -v option when running the container to mount a directory outside the container to the /output directory inside the container, allowing us to export the generated image to the mounted directory.
Note that this is just an example Dockerfile and may need to be modified to suit your specific use case.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment