
โ๏ธ Vanilla JavaScript + Vite ํ๊ฒฝ์์ p5.js๋ฅผ ์์ ํ๊ณ ํ์ฅ์ฑ ์๊ฒ ์ฌ์ฉํ๊ธฐ ์ํ ํต์ฌ ๊ฐ๋
p5.js๋ ์ฐฝ์์ ์ธ ์ฝ๋ฉ์ ์ํ ๊ฐ๋ ฅํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ง๋ง, ์ด๋ป๊ฒ ๋ถ๋ฌ์ค๋๋์ ๋ฐ๋ผ ์ฝ๋ ๊ตฌ์กฐ์ ์ ์ง๋ณด์์ฑ์ด ํฌ๊ฒ ๋ฌ๋ผ์ง๋๋ค.
๊ฐ์ฅ ํฐ ๋ถ๊ธฐ์ ์ ๋ฐ๋ก:
๐น ์ ์ญ ๋ชจ๋(Global Mode)
๐น ์ธ์คํด์ค ๋ชจ๋(Instance Mode)
์ด ๊ธ์์๋ ๋ ๋ฐฉ์์ ๋์ ์๋ฆฌ, ์ฅ๋จ์ , ์ ํฉํ ์ฌ์ฉ ์ฌ๋ก, ๊ทธ๋ฆฌ๊ณ ์ค์ ์ฝ๋ ๋น๊ต๋ฅผ ํตํด ๋ช ํํ ์ง์ด๋ณด๊ฒ ์ต๋๋ค.
https://www.postype.com/@dizicode/post/15021097
https://www.postype.com/@dizicode/post/14862766
https://github.com/processing/p5.js/wiki/Global-and-instance-mode
<script> ํ๊ทธ๋ก HTML์ ์ง์ ๋ก๋ํ๊ฑฐ๋,import 'p5';์ฒ๋ผ ๋ชจ๋๋ก ๋ถ๋ฌ์ค๋ฉด,setup(), draw(), mousePressed() ๋ฑ์ ํจ์ ์ด๋ฆ์ด ์ ์ญ ์ค์ฝํ์ ์๋ ๋ฑ๋ก๋ฉ๋๋ค.setup()๊ณผ draw()๋ฅผ ์ฐพ์ ์คํํฉ๋๋ค.index.html + sketch.js (์ ํต์ ๋ฐฉ์)<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.4/p5.js"></script>
<script src="sketch.js"></script>
</head>
<body></body>
</html>
// sketch.js
function setup() {
createCanvas(400, 400);
background(220);
}
function draw() {
ellipse(mouseX, mouseY, 20, 20);
}
setup, draw, width, height, mouseX ๋ฑ ๋ชจ๋ p5 ๋ณ์/ํจ์๊ฐ ์ ์ญ์ ๋
ธ์ถ๐ก ์์ฝ: "์์์ ํธํ์ง๋ง, ์ ์ ๋ณต์กํด์ง์๋ก ๊ณ ํต๋ฐ๋ ๋ฐฉ์"
new p5()๋ฅผ ํธ์ถํด p5 ์ธ์คํด์ค๋ฅผ ๋ช
์์ ์ผ๋ก ์์ฑcreateCanvas, ellipse, mouseX ๋ฑ)์ ์ธ์คํด์ค์ ๋ฉ์๋/์์ฑ์ผ๋ก ์ ๊ทผsetup, draw)๋ ์ต๋ช
ํจ์ ๋๋ ๋ณ๋ ํจ์๋ก ์ ๋ฌmain.js)
p.์ ๋์ฌ๋ฅผ ๋ฐ๋์ ๋ถ์ฌ์ผ ํฉ๋๋ค.
// main.js
import p5 from 'p5';
new p5((p) => {
// `p`๋ p5 ์ธ์คํด์ค โ ์ ์ญ ๋ณ์ ์์ด ๋ชจ๋ ๊ธฐ๋ฅ์ ์ ๊ทผ ๊ฐ๋ฅ
p.setup = () => {
p.createCanvas(400, 400);
p.background(220);
};
p.draw = () => {
p.ellipse(p.mouseX, p.mouseY, 20, 20);
};
});
๐ก ์์ฝ: "์ด๊ธฐ ์ง์ ์ฅ๋ฒฝ์ ์์ง๋ง, ์ฅ๊ธฐ์ ์ผ๋ก ํจ์ฌ ๊ฑด๊ฐํ ์ ํ"
p5 ์ธ์คํด์ค ๋ชจ๋๋ ํด๋์ค ๊ธฐ๋ฐ ๊ตฌ์กฐ์ ๊ถํฉ์ด ๋งค์ฐ ์ข์ต๋๋ค.
ํนํ ์ฌ๋ฌ ํ๋ผ๋ฏธํฐ๋ฅผ ์กฐ์ ํ๊ฑฐ๋, ์ฌ์ฌ์ฉ ๊ฐ๋ฅํ ์ปดํฌ๋ํธ๋ฅผ ๋ง๋ค ๋ ์ ๋ฆฌํฉ๋๋ค.
main.js ์์์ sketch.js๋ฅผ ๋ถ๋ฌ์ค๋ ์์์ ๋๋ค.
main.js// main.js
import p5 from 'p5';
import CircleSketch from './sketch.js';
const sketch = new p5((p) => {
const circleSketch = new CircleSketch(p, document.body);
circleSketch.init();
});
sketch.js// sketch.js
export default class CircleSketch {
constructor(p, canvasParent) {
this.p = p;
this.parent = canvasParent;
this.radius = 20;
this.color = 255;
}
init() {
this.p.setup = () => {
const canvas = this.p.createCanvas(400, 400);
canvas.parent(this.parent); // ํน์ DOM ์์์ ์บ๋ฒ์ค ์ฝ์
this.p.background(30);
};
this.p.draw = () => {
this.p.background(30, 20); // ํ๋ฆฟํ ํธ๋ ์ผ ํจ๊ณผ
this.p.fill(this.color);
this.p.noStroke();
this.p.ellipse(this.p.mouseX, this.p.mouseY, this.radius);
};
// ์ธ๋ถ์์ ์กฐ์ ๊ฐ๋ฅํ API
this.p.keyPressed = () => {
if (this.p.key === ' ') this.radius += 5;
};
}
}
โ ์ด๋ฐ ๊ตฌ์กฐ๋