p5js/lib/utils.js
2023-01-06 11:00:34 +08:00

122 lines
2.9 KiB
JavaScript

function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
}
function loadJavaScript(path) {
const script = document.createElement("script");
script.src = path;
document.head.appendChild(script);
}
function playdemos(list, delay = 10) {
let fps = frameRate();
fps = 60;
let n = floor((frameCount / (delay * fps)) % list.length);
let func = list[n];
func();
}
function drawGrid(color = 255, fade = 32, offset = 10) {
push();
colorMode(RGB);
stroke(color, fade);
strokeWeight(1);
for (let x = 0; x < width; x += offset) line(x, 0, x, height);
for (let y = 0; y < height; y += offset) line(0, y, width, y);
pop();
}
function textInfo(title, date, name = "赵海洋爸爸", color = 255) {
push();
colorMode(RGB);
fill(color);
noStroke();
text(`作品:${title}`, 30, height - 70);
text(`作者:${name}`, 30, height - 50);
text(`日期:${date}`, 30, height - 30);
pop();
}
function drawVector(vector, color = "#FFFFFF") {
push();
fill(color);
stroke(color);
line(0, 0, vector.x, vector.y);
circle(0, 0, 4);
translate(vector.x, vector.y);
rotate(vector.heading());
triangle(0, 0, -4, -2, -4, +2);
pop();
}
function vectorProjection(v1, v2) {
const v2n = v2.copy().normalize();
const sp = v1.dot(v2n);
return v2n.setMag(sp);
}
function star(x, y, radius1, radius2, npoints) {
let angle = TWO_PI / npoints;
let halfAngle = angle / 2.0;
beginShape();
for (let a = 0; a < TWO_PI; a += angle) {
let sx = x + cos(a) * radius2;
let sy = y + sin(a) * radius2;
vertex(sx, sy);
sx = x + cos(a + halfAngle) * radius1;
sy = y + sin(a + halfAngle) * radius1;
vertex(sx, sy);
}
endShape(CLOSE);
}
// cartesian to polar
function cartesianToPolara(x, y) {
let v = createVector(x, y);
return { r: v.mag(), θ: createVector(1, 0).angleBetween(v) };
}
// polar to cartesian
function polarToCartesian(r, θ) {
return { x: r * cos(θ), y: -r * sin(θ) };
}
function drawRect(x, y, w, h, c = "bottom") {
push();
switch (c) {
case "top":
break;
case "left":
break;
case "right":
break;
default:
rect(x - w / 2, y - h, w, h);
break;
}
pop();
}
function luoxuanxian(x, y) {
push();
noFill();
stroke("#FFDD33");
strokeWeight(4);
translate(x, y);
beginShape();
for (let θ = 0; θ < PI * 6; θ += 0.1) {
let a = 0;
let b = 2;
let r = a + b * θ;
let v = polarToCartesian(r, θ);
vertex(v.x, v.y);
}
endShape();
pop();
}