簡體   English   中英

如何在兩個不同的草圖/畫布之間共享調用 P5.js 函數的方法?

[英]How can I share methods that call P5.js functions between two different sketches/canvases?

有沒有辦法在兩個不同的草圖/畫布之間共享通用方法? 它僅在我不引用任何 P5.js 方法時才有效。

在下面的示例中,有兩個草圖,每個草圖都使用 P5.js 的實例模式加載到不同的 canvas 元素中。

我希望能夠編寫一個使用 P5.js 方法並且每個草圖都可以訪問的 function。

基本上,如果沒有必要,我會盡量避免在兩個草圖中重復代碼。

謝謝

 // Globals easily shared between sketches // no P5.js methods here const canvasW = 521 const canvasH = 322; // Global function that doesn't work because // it isn't in a p5 object?? // How to set this up so we can share a method // across more than one sketch/canvas?? const draw_rect = function() { rect(100, 100, 10, 10); // no context for the rect() method here p55.rect(100, 100, 10, 10); // no context for p55 here unlike in the code below. }; // Sketch 1 const sketch1 = (p55) => { p55.setup = () => { p55.createCanvas(canvasW, canvasH); }; p55.draw = () => { p55.background(76, 123, 199); p55.fill(47, 123); p55.noStroke(); p55.rect(p55.mouseX, p55.mouseY, 47, 47); draw_rect(); // breaks }; }; let myp5_sketch1 = new p5(sketch1, "sketch1"); // Sketch 2 const sketch2 = (p55) => { p55.setup = () => { p55.createCanvas(canvasW, canvasH); }; p55.draw = () => { // including some example drawing code p55.background(76, 47, 123); p55.fill(255, 199); p55.noStroke(); p55.ellipse(p55.mouseX, p55.mouseY, 47, 47); draw_rect(); // breaks }; }; let myp5_sketch2 = new p5(sketch2, "sketch2");
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Sketch</title> <script src="https.//cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script> </head> <body> <div id="sketch1"> <h1>Sketch1</h1> </div> <div id="sketch2"> <h1>Sketch2</h1> </div> <script src="sketch.js"></script> </body> </html>

p5 object 需要是 function 的參數:

const draw_rect = function(p55) {
    p55.rect(100, 100, 10, 10);
};
const sketch1 = (p55) => {
    // [...]
    p55.draw = () => {
        // [...]
       
        draw_rect(p55);
    }
}
const sketch2 = (p55) => {
    // [...]
    p55.draw = () => {
        // [...]
       
        draw_rect(p55);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM