Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

code snippets - How do I include a runnable p5.js sketch in a StackOverflow question?

If I have a question about a p5.js sketch, how can I include my code in the question such that people looking at the question can quickly test my code to see what I'm trying to do or what is wrong?

I know I can include code using the {} toolbar button, which uses the indent by 4 spaces syntax for including code, or use the triple back-tick syntax like so:

function setup() {
    createCanvas(windowWidth, windowHeight);
    background(100);
}

function draw() {
    ellipse(mouseX, mouseY, 20, 20);
}

However, in order for someone reading or answering a question, they have to copy and paste this code into a p5.js editor such as the one on p5js.org or openprocessing.org.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Any time you are asking a question about a p5.js sketch or topic, you should use the JavaScript/HTML/CSS snippet capability of StackOverflow if at all possible.

Code Sample vis JavaScript/HTML/CSS Snippet in the editor

When you insert a Snippet you will see a UI with three textboxes: one for JavaScript, one for HTML, and one for CSS. Each of these textboxes are optional, and your sketch javascript should generally just go in the Javascript textbox. However, in order to make a p5.js sketch runnable, you will need to include the p5.js library. You can do this by clicking the "Add an external library" button and entering the hosted CDN url for the version of p5.js you are using (e.g. https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js).

Add an external library button

Once you have done that you should be able to enter your sketch code, click the run button, and see your sketch in action!

A p5.js sketch running in the snippet editor

And once you click the "Save & insert into post" button, this is what the result will look like:

function setup() {
    createCanvas(windowWidth, windowHeight);
    background(100);
}

function draw() {
    ellipse(mouseX, mouseY, 20, 20);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...