Digital Aquarium with Swimming Fish in p5.js: Dynamic Artwork with Click-to-Add Feature

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About This Article
This article is created using an automated generation workflow leveraging generative AI. By using hypothetical data and browser operations, you will learn the use cases, mechanisms, and observation points for troubleshooting in p5.js. No access to real services or personal information is performed.

Verification Status:In reviews conducted up to 2026-10-30, official documentation was cross-referenced with fixed sources from saved Daily Code, and Node.js syntax check results were recorded. Actual browser operations, rendering, and CDN responses are unverified. Screen descriptions represent expected values from the code and are distinguished from actual measurements.

ItemDetails
TargetModern browsers such as Chrome, Edge, and Firefox (hardware compatibility unconfirmed)
Libraries Usedp5.js (version in tutorial: 1.11.13)
CostThe demo source itself does not require a paid API. Data transmission fees and usage conditions depend on the environment.
DataHypothetical data within the page. No authentication, location information, or corporate data required.
Learning OperationIncrease the number of fish with clicks and observe the movement of the aquarium

Why Try This Technology?

Tutorials like maps or comics where 'something moves when you open the screen' are appealing because of the short distance between code and results. p5.js is a library that allows you to learn variables, coordinates, loops, and events using shape drawing as an entry point. Without using complex game engines, we will make fish move on the screen using only HTML and a short JavaScript snippet. The fish are not photographs, but combinations of ellipses and triangles, starting with just two. By using buttons to increase or clear them, the relationship between arrays and the screen becomes apparent.

When creating a working sample, rather than stopping at the fact that the interface visually moved, it is necessary to distinguish which input modified which variable and which process updated the rendering. In this tutorial material, those changes are explicitly shown on the screen. When integrating into an actual service, please design the authentication and data persistence processes separately.

Try First: Live Demo and Expected Results

Opening the live demo is expected to show two fish on a dark blue background. Compare the number of times the add button was pressed with the count displayed at the bottom of the screen. Next, pressing the clear button leaves only the background. At this point, it is important that '0 fish' is displayed. You can distinguish whether they are simply hidden or if the management array has actually been emptied. While the Canvas element is graphical, outputting states such as the fish count as text is also beneficial for accessibility.

Check Before Operation: If the Public Demo Cannot Be Opened

The public demo ispublic and operation-unverified. If you cannot open it, retrieve themain HTMLandmain JavaScriptfrom their respective raw views on GitHub, and save them in theindex.htmlsame new folderapp.jswith the names. Because the folder containing the README does not have an execution HTML, the README alone will not make it run.READMEweb/folder has no execution HTML, so the README alone will not make it run.

  1. On a PC where Python 3 is available, open the folder containing these two files. On Windows, typingpowershellinto the folder's address bar allows you to open PowerShell in that folder.

  2. For Windows, runpy -3 -m http.server 8000 --bind 127.0.0.1, and for Linux/macOS, runpython3 -m http.server 8000 --bind 127.0.0.1. If Python is not installed, use another local HTTP server. Administrator privileges are not required.

  3. Openhttp://127.0.0.1:8000/ in a browser on the same PC, and check the Console and Network tabs in the developer tools. The initial text is designed to becomeREADY: JavaScriptを読み込み中、draw() once it proceeds toRUNNING: 魚 2匹.Seeing RUNNING alone does not prove that the canvas rendering was successful. Please visually verify the blue background and the display and movement of the two fish.

  4. 魚を追加Pressing the button once changes the count to 3, and pressing空にする changes it to 0. The upper limit is 30 fish. If the count does not change, check the button ID (add / reset) and any console errors. To stop, pressCtrl+C in the terminal where the server was started.

file://Because direct viewing viap5@1.11.13 varies by environment, HTTP serving is recommended. Since the HTML loads from a third-party CDN, an internet connection and organizational network permission are required. While there is no processing to send the fish input values to an external server, communication to retrieve the CDN does occur.

Overview of the mechanism

flowchart LR
    A["入力やクリック"] --> B["イベントを受ける"]
    B --> C["p5.js のAPI"]
    C --> D["状態と描画を更新"]
    D --> E["見た目と文字で確認"]

This diagram is a conceptual illustration for learning purposes and does not represent the internal implementation of the browser or the details of network communication. Regardless of the library used, tracing "which variable the operation reaches" remains the same.

How it works: Understanding the API

As a rule, setup runs initial preparation only once, while draw repeatedly renders frames. The object representing the fish has position and velocity values x, y, and v. Incrementing or decrementing x by v within draw and rendering it at a new location in the next frame creates the appearance of swimming. Using translate and scale allows you to change the rendering position and orientation of the entire shape without having to calculate each part of the fish individually. If you do not save and restore the transformation state using push and pop, the coordinate transformations will affect subsequent fish, causing them to appear in unexpected positions.

How to Read Minimal Code

function setup() { createCanvas(640, 350); }
function draw() { background(19, 62, 98); ellipse(80, 80, 53, 25); }

The above is an excerpt highlighting the key points of the API. It is not a complete, standalone executable file.Please check the README and demo files on the Daily Code side for the complete set of HTML and implementation required to run it.Trace which functions select HTML elements and which lines update numeric values, and test them with known dummy values.

Modify Only One Condition and Compare

At the beginning of the actualapp.js, there isconst fish=[{x:50,y:80,v:1},{x:220,y:160,v:-1.5}];. First, change only the firstv:1tov:2, reload the browser, and compare whether the first fish moves faster. Do not change the size of the fish or the speed of the second fish. Since the actual codedraw()addsf.x+=f.vper, this represents the amount of movement per frame, and there is no guarantee that the speed per second will remain the same if the device frame rate changes.

The original code already includes the process of horizontally flippingv<0fish usingscale(-1,1), and the process of isolating transformations per fish usingpush() / pop(). There is no need to add any additional flipping logic. After making your comparison, revert tov:1and reload.

The procedure for comparison is to record the initial value, change only one part, and verify whether the result appears in the expected location. Changing multiple inputs at once makes it impossible to determine what had an effect. Be sure to validate the process including reverting to the state before the changes.

Where to look when a failure occurs

Performance drops when starting to render thousands of fish in the same frame. The sample sets an upper limit on the number of fish. Rendering may be throttled while the browser tab is in the background, making it unsuitable as-is for a strict real-time simulator. When resizing the screen, link the canvas dimensions with the fish wrap-around boundaries. Because p5.js has major API changes, the version used in this learning material is fixed to the 1.x series, and compatibility will be checked when updating to the 2.x series later.

Observed statePoints to isolateExample of resolution
The screen does not change from the initial stateScript acquisition, initialization, and event registrationCheck Console, Network, and script tags
The display changes but the meaning is incorrectInput values, arrays, units, and update targetsFix values and check one condition at a time
The button cannot be clickedSelectors and DOM generation orderCheck the HTML to ensure IDs match
It does not work on certain devices onlyBrowser features, permissions, CDN, and performanceRecord the device, version, and reproduction steps

Errors within the browser and failures on a public web server are different. The former is investigated using error details in the developer tools, while the latter is examined through HTTP responses and asset delivery conditions. Refraining from describing an unknown failure as a success enhances the reliability of technical notes.

Application to work and studies

It can be expanded into exhibits, educational materials, interactive guides for event venues, and data-responsive illustrations. For more practical applications, click-based additions can be replaced with operational events. However, publishing actual operational data to a public browser may lead to information leakage. First, finalize the screen and state design using only dummy data.

Decisions to Make Before Implementation

When publishing to readers, determine where the displayed data comes from, who can modify it, the types of information remaining on the screen, and verification items when updating libraries. The current demo has neither login nor server persistence. Therefore, before adding operational features, we recommend distinguishing between the "minimum portion that displays as expected" and the "portion requiring operational reliability, permissions, and backups." Since third-party CDNs involve external communication, prior confirmation is required regarding corporate network policies.

Comparison with Alternative Methods

MethodSuitable ScenarioPoints to Note
p5.jsScenarios matching goals such as increasing fish by clicking and observing aquarium motionRequires management of dependency library updates and terms of use
Browser Standard APIBuilding small features in-houseVerify specifications and compatibility independently
Static Images and TablesExplanations that do not require user interactionUnable to experience state changes on the spot

Libraries are tools to be chosen when needed. Compare them by aligning your goals with the learning curve. Avoiding "adding a library just for the sake of it" makes small-scale pages easier to maintain.

GitHub Sample

The blog body is assigned the role of explaining the background and concepts, while Daily Code provides executable and modifiable code. APIs for posting to and saving on external services are not included.

Official and Primary Sources

Reviewed Documentation Scope: Re-verified the implementation of the official p5.js setup, draw, and push functions along with the fixed commit on October 30, 2026. Actual CDN responses and browser rendering have not been verified.

Additional Notes on Verification Scope

You can refer to the fixed commit for Daily Code and the existing Node.js syntax check results. However, actual browser rendering, library CDN responses, and operation across all devices have not been verified. Please verify actual execution in your environment using the Console and Network tabs.

Document information

Article title
Digital Aquarium with Swimming Fish in p5.js: Dynamic Artwork with Click-to-Add Feature
Published
Updated
Source
https://papanda925.com/?p=18358&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL