[英]p5.js – Smoothly morphing random shape
首先,我是js和p5.js的初學者。 我對這個程序的目標是平滑變形的隨機形狀 。 我對calculateShape()函數和drawShape()函數感到滿意,但是當涉及到變形(updateShape())時,它確實很難看。 我認為將當前數組保存到臨時數組中,然后循環遍歷該數組,並向每個索引的每個x和y添加一個隨機數,然后在該索引處替換舊的x和y,這可能是個好主意。 主要問題是,它總是在屏幕上添加新形狀,而不是更改現有形狀的頂點值。 有人可以給我提示或指出我的錯誤嗎? 先感謝您!
var c1;
var c2;
var c3;
var centerX;
var centerY;
var fb;
var radius;
var angle;
var shape = [];
var temp;
/*function to calculate the inital shape*/
function calculateShape() {
//calculate coordinates and save into array
for (var i = 0; i < fb; i++) {
var x = cos(angle * i) * radius + random(-77,77);
var y = sin(angle * i) * radius + random(-77,77);
var v = createVector(x, y);
shape.push(v);
}
}
/*function for morphing the shape*/
function updateShape() {
var temp = shape;
for (var i = 0; i < shape.length - 1; i++) {
var x = temp[i].x + random(-1, 1);
var y = temp[i].y + random(-1, 1);
var p = temp[i];
var v = createVector(x, y);
shape.splice(p,1);
shape.push(v);
}
}
/*function for drawing the shape on the screen*/
function createShape(){
beginShape();
curveVertex(shape[shape.length-1].x, shape[shape.length-1].y);
for (var i = 0; i < shape.length; i++){
curveVertex(shape[i].x, shape[i].y);
}
curveVertex(shape[0].x, shape[0].y);
endShape(CLOSE);
}
function setup() {
createCanvas(windowWidth, windowHeight);
smooth();
background(250);
//frameRate(2);
// defining possible colors
c1 = color(0, 196, 181, 235);
c2 = color(50, 227, 232, 235);
c3 = color(248, 49, 62, 255);
var colors = [c1, c2, c3];
//center of the window
centerX = windowWidth/2;
centerY = windowHeight/2;
//defining all variables
fb = 8;
angle = radians(360 / fb);
radius = random(120, 140);
//calling thefunction that initalises the shape
calculateShape();
}
function draw() {
translate(centerX, centerY);
blendMode(BLEND);
fill(c3);
noStroke();
createShape();
updateShape();
}
主要問題是,它總是在屏幕上添加新形狀,而不是更改現有形狀的頂點值。
當然,您只需要在重新繪制之前清除屏幕即可。 因此,在draw
,使用setup
background(250)
的background(250)
重置背景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.