function setup() {
const canvas = createCanvas(800, 600);
canvas.parent('canvas');
noLoop();
colorMode(HSL, 360, 100, 100);
}
function draw() {
background(255);
stroke(0);
fill(0);
function drawKoch(turtle, depth) {
if (depth > 0) {
moveForward(turtle.x + cos(turtle.angle) * 3, turtle.y + sin(turtle.angle) * 3);
drawKoch(turtle, depth - 1);
turn(60);
drawKoch(turtle, depth - 1);
turn(-120);
drawKoch(turtle, depth - 1);
turn(60);
moveForward(turtle.x - cos(turtle.angle) * 3, turtle.y - sin(turtle.angle) * 3);
} else {
moveForward(turtle.x, turtle.y);
}
}
let angle = 0;
let x = width / 2;
let y = height / 2;
let depth = 3;
function moveForward(dx, dy) {
x += dx;
y += dy;
}
function turn(degrees) {
angle += degrees * PI / 180;
}
drawKoch({x, y, angle}, depth);
}
function mouseDown() {
save();
push();
translate(mouseX, mouseY);
rotate(mouseX * 0.001, 0, 0);
draw();
pop();
translate(-mouseX, -mouseY);
load();
}
function mouseUp() {
pop();
translate(-mouseX, -mouseY);
load();
}
function mouseMove(x, y) {
translate(x, y);
}
function keyDown() {
if (key === ' ' && !isSaving) {
save();
push();
translate(mouseX, mouseY);
rotate(mouseX * 0.001, 0, 0);
draw();
pop();
translate(-mouseX, -mouseY);
load();
isSaving = true;
}
}
function keyUp() {
pop();
translate(-mouseX, -mouseY);
load();
isSaving = false;
}
// 添加颜色控制
function colorInput() {
const input = createSlider(0, 100, 50, "Hue");
input.onChange = (e) => {
angle = e.target.value * 2 * PI / 100;
};
}
// 添加交互按钮
function addButton() {
const button = createButton("生成分形");
button.onClick = () => {
draw();
};
}
addButton();
colorInput();
console