Starfields
Still setting up environments. This sketch uses P5 in instance mode, including it as a module for a Parcel build, along with an optional p5 library. (p5 dom and sound libraries are included with the npm module but must be imported separately.)
import p5 from 'p5';
import 'p5/lib/addons/p5.dom';
import Star from './star';
const s = (p) => {
p.setup = function () {
setSize();
let myCanvas = p.createCanvas(w, h);
myCanvas.parent('paint');
for (let i = 0; i < 800; i++) {
stars[i] = new Star(p);
}
p.draw = function () {
p.background(0);
p.translate(p.width / 2, p.height / 2);
for (let i = 0; i < stars.length; i++) {
stars[i].update();
stars[i].show();
}
};
let myp5 = new p5(s);
This will set the ground for playing well with other modules in the future.
The Star class is a custom module and uses some p5 functions so a reference to the Processing name and function space is passed on the constructor.
export default class Star {
constructor(p) {
this.p = p;
}
update() {
}
show() {
this.p.fill(255);
this.p.noStroke();
...
Touch functions in p5 handle both mouse clicks and screen touches and registers both to the mouseX and mouseY properties
p.touchMoved = function () {
tweak();
return false; // prevent default behavior
};
p.touchStarted = function () {
tweak();
return false;
};
The location of the click/touch on the x axis tweaks the speed and the y tweaks the rotation
function tweak() {
speed = p.map(p.mouseX, 0, p.width, 0, 50);
r_inc = p.map(p.mouseY, 0, p.height, 0.01, 0.1);
}
Page Layout
The layout expands the canvas to fill as much of the screen as it can. Using flexbox makes this fairly straight-forward
<body>
<div id="page">
<div id="header">
<h3>Day 2 - Seeing Stars</h3>
</div>
<div id="paint"></div>
<div id="footer">©2019 kentskyo</div>
</div>
<script src="index.js"></script>
</body>
html,
body {
margin: 0;
padding: 0;
overflow: hidden;
}
#page {
height: 100vh;
display: flex;
flex-direction: column;
}
#header {
text-align: center;
background-color: black;
color: rgb(153, 155, 155);
}
#footer {
text-align: center;
background-color: black;
color: rgb(153, 155, 155);
font-size: 10pt;
}
canvas {
display: block;
}
#paint {
display: flex;
flex-grow: 1;
background: black;
}
Resizing the Canvas
During p5 setup or window resize events a setSize function is called. This function uses the P5 dom addon, included as a module above
let c, w, h;
function setSize() {
if (!c) c = p.select("#paint");
w = c.elt.clientWidth;
h = c.elt.clientHeight;
}
p.windowResized = function () {
setSize();
p.resizeCanvas(w, h);
};